Polycarp is playing a new computer game. This game has $$$n$$$ stones in a row. The stone on the position $$$i$$$ has integer power $$$a_i$$$. The powers of all stones are distinct.Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone). When Polycarp destroys the stone it does not exist any more.Now, Polycarp wants two achievements. He gets them if he destroys the stone with the least power and the stone with the greatest power. Help Polycarp find out what is the minimum number of moves he should make in order to achieve his goal.For example, if $$$n = 5$$$ and $$$a = [1, 5, 4, 3, 2]$$$, then Polycarp could make the following moves:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the rightmost stone. After this move $$$a = [5, 4, 3]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game. Please note that in the example above, you can complete the game in two steps. For example:   Destroy the leftmost stone. After this move $$$a = [5, 4, 3, 2]$$$;  Destroy the leftmost stone. After this move $$$a = [4, 3, 2]$$$. Polycarp destroyed the stones with the greatest and least power, so he can end the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of stones. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$) — the power of the stones.

For each test case, output the minimum number of moves required to destroy the stones with the greatest and the lowest power.

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, mx = a.index(a.min), a.index(a.max)
    puts [[mn, mx].max + 1, n - [mn, mx].min, n - mn + mx + 1, n - mx + mn + 1].min
end

t = gets.to_i
for i in 0...t
	n = gets.to_i
	a = gets.split.map(&:to_i)
	x, y = [a.index(a.min), a.index(a.max)].sort
	puts [y + 1, n - x, x + 1 + n - y].min
end

gets.to_i.times do
  n=gets.to_i
  a=gets.split.map(&:to_i)
  s,t=[a.index(a.min),a.index(a.max)].sort
  puts [t+1,n-s,s+1+n-t].min
end

gets.to_i.times do
    n = gets.to_i
    a = gets.split.map &:to_i
    mn, mx = a.index(a.min), a.index(a.max)
    puts [[mn, mx].max + 1, n - [mn, mx].min, n - mn + mx + 1, n - mx + mn - 1].min
end


Is it rated?Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before and after the round is known.It's known that if at least one participant's rating has changed, then the round was rated for sure.It's also known that if the round was rated and a participant with lower rating took a better place in the standings than a participant with higher rating, then at least one round participant's rating has changed.In this problem, you should not make any other assumptions about the rating system.Determine if the current round is rated, unrated, or it's impossible to determine whether it is rated of not.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of round participants. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 4126) — the rating of the i-th participant before and after the round, respectively. The participants are listed in order from the top to the bottom of the standings.

If the round is rated for sure, print "rated". If the round is unrated for sure, print "unrated". If it's impossible to determine whether the round is rated or not, print "maybe".

NoteIn the first example, the ratings of the participants in the third and fifth places have changed, therefore, the round was rated.In the second example, no one's rating has changed, but the participant in the second place has lower rating than the participant in the fourth place. Therefore, if the round was rated, someone's rating would've changed for sure.In the third example, no one's rating has changed, and the participants took places in non-increasing order of their rating. Therefore, it's impossible to determine whether the round is rated or not.

n=gets.to_i
a=[]
b=[]
rated=false
n.times do
    x, y=gets.split.map &:to_i
    a<<x
    b<<y
    rated=true if x!=y
end
c=b.sort.reverse
if rated
    puts "rated"
else
    puts (c==b ? "maybe" : "unrated")
end

n = gets.chomp.to_i

ratings = []

n.times do
  a, b = gets.chomp.split(" ").map(&:to_i)
  if a != b then
    puts "rated"
    exit
  else
    ratings << b
  end
end

(n-1).times do |i|
  if ratings[i] < ratings[i+1] then
    puts "unrated"
    exit
  end
end
puts "maybe"


Screen resolution of Polycarp's monitor is $$$a \times b$$$ pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates $$$(x, y)$$$ ($$$0 \le x < a, 0 \le y < b$$$). You can consider columns of pixels to be numbered from $$$0$$$ to $$$a-1$$$, and rows — from $$$0$$$ to $$$b-1$$$.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.

In the first line you are given an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. In the next lines you are given descriptions of $$$t$$$ test cases. Each test case contains a single line which consists of $$$4$$$ integers $$$a, b, x$$$ and $$$y$$$ ($$$1 \le a, b \le 10^4$$$; $$$0 \le x < a$$$; $$$0 \le y < b$$$) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that $$$a+b>2$$$ (e.g. $$$a=b=1$$$ is impossible).

Print $$$t$$$ integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.

NoteIn the first test case, the screen resolution is $$$8 \times 8$$$, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.

T = gets.to_i

T.times do
  a, b, x, y = gets.split.map(&:to_i)

  a1 = a * y
  a2 = a * (b - y - 1)
  a3 = b * x
  a4 = b * (a - x - 1)

  puts [a1, a2, a3, a4].max
end


Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n × m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows:  Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 × 2.  Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.

The first line will contain two single-space separated integers n and m (1 ≤ n, m, n·m ≤ 5·105) — the number of rows and columns respectively. Then n lines follow, each contains exactly m characters — the description of the grid. Each character describes a cell and is either one of these:    "1" - "4" — a pipe segment of one of four types as described above  "." — an empty cell

Print a single integer denoting the number of possible final non-leaking pipe systems modulo 1000003 (106 + 3). If there are no such configurations, print 0.

NoteFor the first example, the initial configuration of the grid is as follows.   The only two possible final non-leaking pipe configurations are as follows:    For the second example, the initial grid is already leaking, so there will be no final grid that is non-leaking.For the final example, there's only one possible non-leaking final grid as follows.

MOD   = 1000003
UP    = 0b1000
DOWN  = 0b0001
LEFT  = 0b0100
RIGHT = 0b0010
TILES = [
  0b1100,
  0b0101,
  0b0011,
  0b1010,
]
%w(UP DOWN LEFT RIGHT).each {|dir|
  eval <<EOS
def #{dir.downcase}?(v)
  v & #{dir} != 0
end
EOS
}

def top_down(r,c,g)
  a = Array.new(c)
  r.times { |i|
    row = g[i]
    c.times { |j|
      if !row[j].nil?
        v = down?(row[j]) ? 1 : -1
        v = -v if i.odd?
        if a[j].nil?
          a[j] = v
        else
          return nil if a[j] != v
        end
      end
    }
  }
  a
end

def rot(v)
  ((v << 1) & 0b1000) | ((v >> 1) & 1)
end
def rotate(r,c,g)
  c.times.map { |j| r.times.map { |i| g[i][j] && rot(g[i][j]) } }
end

r,c=gets.split.map(&:to_i)
g = []
# r.times {
#   g << gets.chomp.chars.map{ |c|
#     c == '.' ? nil : TILES[c.to_i-1]
#   }
# }
s = STDIN.read
r.times {|i|
  k = []
  (i*(c+1)).upto(i*(c+1)+c-1) {|j|
    k << (s[j] == '.' ? nil : TILES[s[j].to_i-1])
  }
  g << k
}

td = top_down r, c, g
rl = top_down c, r, rotate(r,c,g)

def power2(n)
  return 2**n if n <= 1
  v = (power2(n/2)**2) % MOD
  v = (v*2) % MOD if n.odd?
  v
end

if rl.nil? || td.nil?
  puts '0'
else
  puts power2 (rl+td).count(&:nil?)
end

MOD   = 1000003
UP    = 0b1000
DOWN  = 0b0001
LEFT  = 0b0100
RIGHT = 0b0010
TILES = [
  0b1100,
  0b0101,
  0b0011,
  0b1010,
]
%w(UP DOWN LEFT RIGHT).each {|dir|
  eval <<EOS
def #{dir.downcase}?(v)
  v & #{dir} != 0
end
EOS
}

r,c=gets.split.map(&:to_i)
g = []
r.times {
  g << gets.chomp.chars.map{ |c|
    c == '.' ? nil : TILES[c.to_i-1]
  }
}

def top_down(r,c,g)
  a = Array.new(c)
  r.times { |i|
    row = g[i]
    c.times { |j|
      if !row[j].nil?
        v = down?(row[j]) ? 1 : -1
        v = -v if i.odd?
        if a[j].nil?
          a[j] = v
        else
          return nil if a[j] != v
        end
      end
    }
  }
  a
end

def rotate(r,c,g)
  c.times.map { |j| r.times.map { |i| g[i][j] } }
end

td = top_down r, c, g
rl = top_down c, r, rotate(r,c,g)

if rl.nil? || td.nil?
  puts '0'
else
  puts 2**((rl+td).count(&:nil?)) % MOD
end


Now Vasya is taking an exam in mathematics. In order to get a good mark, Vasya needs to guess the matrix that the teacher has constructed!Vasya knows that the matrix consists of n rows and m columns. For each row, he knows the xor (bitwise excluding or) of the elements in this row. The sequence a1, a2, ..., an denotes the xor of elements in rows with indices 1, 2, ..., n, respectively. Similarly, for each column, he knows the xor of the elements in this column. The sequence b1, b2, ..., bm denotes the xor of elements in columns with indices 1, 2, ..., m, respectively.Help Vasya! Find a matrix satisfying the given constraints or tell him that there is no suitable matrix.

The first line contains two numbers n and m (2 ≤ n, m ≤ 100) — the dimensions of the matrix. The second line contains n numbers a1, a2, ..., an (0 ≤ ai ≤ 109), where ai is the xor of all elements in row i. The third line contains m numbers b1, b2, ..., bm (0 ≤ bi ≤ 109), where bi is the xor of all elements in column i.

If there is no matrix satisfying the given constraints in the first line, output "NO". Otherwise, on the first line output "YES", and then n rows of m numbers in each ci1, ci2, ... , cim (0 ≤ cij ≤ 2·109) — the description of the matrix. If there are several suitable matrices, it is allowed to print any of them.

N, M = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
bs = gets.split.map(&:to_i)
if as.inject(:'^') != bs.inject(:'^')
    puts 'NO'
    exit
end

ans = Array.new(N){Array.new(M, 0)}
(N-1).times do |i|
    ans[i][-1] = as[i]
end
(M-1).times do |j|
    ans[-1][j] = bs[j]
end
ans[N-1][M-1] = as[-1] ^ bs[0, M-1].inject(0, :'^')

puts 'YES'
N.times do |i|
    puts ans[i].join(' ')
end

N, M = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
bs = gets.split.map(&:to_i)
if as.inject(:'^') != bs.inject(:'^')
    puts 'NO'
    exit
end

ans = Array.new(N){Array.new(M, 0)}
(N-1).times do |i|
    ans[i][-1] = as[i]
end
(M-1).times do |j|
    ans[-1][j] = bs[j]
end
ans[N-1][M-1] = as[-1] ^ bs[0, M-1].inject(0, :'^')
N.times do |i|
    puts ans[i].join(' ')
end


The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thus, Sereja orders a number of pizzas so they can eat right after the end of the competition.Teams plan to train for n times during n consecutive days. During the training session Sereja orders exactly one pizza for each team that is present this day. He already knows that there will be ai teams on the i-th day.There are two types of discounts in Sereja's favourite pizzeria. The first discount works if one buys two pizzas at one day, while the second is a coupon that allows to buy one pizza during two consecutive days (two pizzas in total).As Sereja orders really a lot of pizza at this place, he is the golden client and can use the unlimited number of discounts and coupons of any type at any days.Sereja wants to order exactly ai pizzas on the i-th day while using only discounts and coupons. Note, that he will never buy more pizzas than he need for this particular day. Help him determine, whether he can buy the proper amount of pizzas each day if he is allowed to use only coupons and discounts. Note, that it's also prohibited to have any active coupons after the end of the day n.

The first line of input contains a single integer n (1 ≤ n ≤ 200 000) — the number of training sessions. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 10 000) — the number of teams that will be present on each of the days.

If there is a way to order pizzas using only coupons and discounts and do not buy any extra pizzas on any of the days, then print "YES" (without quotes) in the only line of output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, Sereja can use one coupon to buy one pizza on the first and the second days, one coupon to buy pizza on the second and the third days and one discount to buy pizzas on the fourth days. This is the only way to order pizzas for this sample.In the second sample, Sereja can't use neither the coupon nor the discount without ordering an extra pizza. Note, that it's possible that there will be no teams attending the training sessions on some days.

p = 0
n = gets.to_i

a = gets.split.map &:to_i
s = false
a.each do |i|
    if i < p
        s = true
        break
    elsif i%2 !=  p
        p = 1
    elsif i%2 == p
        p = 0
    end
end

if s or p > 0
    puts "NO"
else
    puts "YES"
end

r=0
gets;gets.split.map(&:to_i).each{|e|
break if r>e
r^=e%2
}
puts [:YES,:NO][r]

n = gets.to_i
as = gets.split.map(&:to_i)
as.each_with_index do |a, i|
  if a < 0 || a.odd? && i == n - 1
    puts 'NO'
    exit
  end
  if a.odd?
    as[i + 1] -= 1
  end
end
puts 'YES'

n = gets.to_i
a = gets.split(" ").map(&:to_i)
ans = 0
a.each do |e|
  break if (e <ans)
  ans = (e - ans)%2
end
print ans>0? "NO" : "YES"

n=gets.to_i-2
a=gets.split.map &:to_i

res="YES"
for i in 0..n
    if a[i]<0
        res="NO"
        break
    end

    if a[i].odd?
        a[i]-=1
        a[i+1]-=1
    end
end
res="NO" if a[-1].odd?

puts res

n=gets.to_i-1
a=gets.split.map &:to_i

n.times { |i|
  if a[i].odd?
    a[i] -= 1
    a[i+1] -= 1
  end
  (puts 'NO'; exit) if a[i] < 0
}
puts (a[n].even?)?'YES':'NO'

n = gets.to_i
a = gets.split.map(&:to_i)
k = 0
a.each do |x|
   break if x-k<0
   k = (x-k)%2
end
puts k>0 ? "NO" : "YES"

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

def meow(n, a)
  n.times do |i|
    return false if a[i] < 0
    if a[i].odd?
      return false if i == n - 1
      a[i + 1] -= 1
    end
  end
end

puts meow(n, a) ? 'YES' : 'NO'

n = gets.to_i
a = gets.strip.split(' ').map(&:to_i)
flag = false
0.upto(n - 1) do |i|
  if flag
    if a[i] == 0
      break
    else
      a[i] -= 1
      flag = !flag
    end
  end

  if a[i] % 2 == 1
    flag = !flag
  else
    if flag == true
      break
    end
  end
end

printf("%s\n", flag ? "NO" : "YES")

require 'set'

parse_int = lambda {gets.split.map{|x| x.to_i}}

gets
pz = parse_int.call

(pz.length-1).times do |i|
  if pz[i].odd?
    if pz[i+1]>0
      pz[i] -= 1
      pz[i+1] -= 1
    else
      puts 'NO'
      exit
    end
  end
end

puts pz[-1].even? ? 'YES' : "NO"

p = 0
n = gets.to_i

a = gets.split.map &:to_i
s = false
a.each do |i|
    if i == p + 1
        p = 1
    elsif i == p+2 or i == p
        p = 0
    else
        s = true
        break
    end
end

if s or p > 0
    puts "NO"
else
    puts "YES"
end

p = 0
n = gets.to_i

a = gets.split.map &:to_i
s = false
a.each do |i|
    if i == p + 1
        p = 1
    elsif i == p+2
        p = 0
    elsif i != p
        puts "NO"
        s = true
        break
    end
end

puts "YES" unless s

r=0
gets.split.map(&:to_i).each{|e|
break if r>e
r^=e%2
}
puts [:YES,:NO][r]

r=0
gets.split.map(&:to_i).each{|e|
break if e>r
r^=e%2
}
puts [:YES,:NO][r]

n = gets.to_i
a = gets.split(" ").map(&:to_i)
ans = 0
a.each do |e|
  break if (ans < e)
  ans = (e - ans)%2
end
print ans>0? "NO" : "YES"

n = gets.to_i
a = gets.split.map(&:to_i)
k = 0
a.each { |x| k = (x-k)%2 }
puts k>0 ? "NO" : "YES"


This problem differs from one which was on the online contest.The sequence a1, a2, ..., an is called increasing, if ai < ai + 1 for i < n.The sequence s1, s2, ..., sk is called the subsequence of the sequence a1, a2, ..., an, if there exist such a set of indexes 1 ≤ i1 < i2 < ... < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.

The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.

In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.

n=gets.to_i
a=gets.split.map &:to_i
m=gets.to_i
b=gets.split.map &:to_i
d=[0]*m
q=[0]*n
p=[-1]*n
n.times{|i|
	mx=0
	m.times{|j|
		mx=[mx,d[j]].max if a[i]>b[j]
		q[i]=d[j]=mx+1 if a[i]==b[j]
	}
	i.times{|j|p[i]=j if a[j]<a[i] and q[j]==q[i]-1}
}
i=q.index(q.max)
l=[]
"#{l<<a[i];i=p[i]}"while i>=0 and q[i]>0
p q.max
puts l.reverse.join " "

n=gets.to_i
a=gets.split.map &:to_i
m=gets.to_i
b=gets.split.map &:to_i
d=[0]*m
q=[0]*n
p=[-1]*m
n.times{|i|
	mx=0
	m.times{|j|
		mx=[mx,d[j]].max if a[i]>b[j]
		q[i]=d[j]=mx+1 if a[i]==b[j]
	}
	i.times{|j|p[i]=j if a[j]<a[i] and q[j]==q[i]-1}
}
i=q.index(q.max)
l=[]
"#{l<<a[i];i=p[i]}"while i>=0
p q.max
puts l.reverse.join " "


You are given a string $$$s$$$ consisting only of characters + and -. You perform some process with this string. This process can be described by the following pseudocode: res = 0for init = 0 to inf    cur = init    ok = true    for i = 1 to |s|        res = res + 1        if s[i] == '+'            cur = cur + 1        else            cur = cur - 1        if cur < 0            ok = false            break    if ok        breakNote that the $$$inf$$$ denotes infinity, and the characters of the string are numbered from $$$1$$$ to $$$|s|$$$.You have to calculate the value of the $$$res$$$ after the process ends.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only lines of each test case contains string $$$s$$$ ($$$1 \le |s| \le 10^6$$$) consisting only of characters + and -. It's guaranteed that sum of $$$|s|$$$ over all test cases doesn't exceed $$$10^6$$$.

For each test case print one integer — the value of the $$$res$$$ after the process ends.

t = gets.to_i
t.times do
    a = []
    b = {}
    cur = 0
    gets.each_char.with_index do |c, i|

        case c
        when '+'
            a << (cur += 1)
        when '-'
            a << (cur -= 1)
        else
            a << cur
        end

        b[cur] = i + 1 unless b.include? cur
    end

    res = 0
    init = 0
    loop do

        if b.include?(-init-1)
            res += b[-init-1]
        else
            res += a.size - 1
            break
        end

        init += 1
    end

    p res
end

def solve
  str = gets.strip
  cur = 0
  h = Hash.new(0)
  str.each_char.with_index { |e, i|
    if e == '+'
      cur += 1
    else
      cur -= 1
      if cur < 0 && h[-cur].zero?
        h[-cur] = i + 1
      end
    end
  }
  res = 0
  (0..str.size).each { |i|
     ck = h[i + 1]
     if ck.zero?
      res += str.size
      break
     else
      res += ck
     end
  }
  puts res
end

gets.strip.to_i.times { solve }

def solve
  str = gets.strip
  cur = 0
  h = Hash.new()
  str.each_char.with_index { |e, i|
    if e == '+'
      cur += 1
    else
      cur -= 1
      if cur < 0 && !h.has_key?(-cur)
        h[-cur] = i + 1
      end
    end
  }
  res = 0
  (0..str.size).each { |i|
    ck = h[i + 1] if h.has_key?(i + 1)
    if ck.nil?
     res += str.size
     break
    else
     res += ck
    end
  }
  puts res
end

gets.strip.to_i.times { solve }

def solve
  str = gets.strip
  cur = 0
  h = Hash.new(0)
  str.each_char.with_index { |e, i|
    if e == '+'
      cur += 1
    else
      cur -= 1
      if cur < 0 && h[-cur].zero?
        h[-cur] = i + 1
      end
    end
  }
  res = 0
  (0..str.size).each { |i|
     ck = h[i + 1]
     if ck.zero?
      res += str.size
      break
     else
      res += h[ck]
     end
  }
  puts res
end

gets.strip.to_i.times { solve }

def solve
  str = gets.strip
  cur = 0
  h = Hash.new(1e7 + 1)
  a = []
  str.each_char.with_index { |e, i|
    if e == '+'
      cur += 1
    else
      cur -= 1
      if cur < 0
        h[-cur] = [h[-cur], i + 1].min
        a << -cur
      end
    end
  }
  res = 0
  (0..str.size).each { |i|
     ck = a.bsearch { |x| x > i}
     if ck.nil?
      res += str.size
      break
     else
      res += h[ck]
     end
  }
  puts res
end

gets.strip.to_i.times { solve }

def solve
  str = gets.strip
  cur = 0
  h = Hash.new(0)
  str.each_char.with_index { |e, i|
    if e == '+'
      cur += 1
    else
      cur -= 1
      if cur < 0 && h[-cur].nil?
        h[-cur] = i + 1
      end
    end
  }
  res = 0
  (0..str.size).each { |i|
     ck = h[i + 1]
     if ck.zero?
      res += str.size
      break
     else
      res += h[ck]
     end
  }
  puts res
end

gets.strip.to_i.times { solve }


On a strip of land of length $$$n$$$ there are $$$k$$$ air conditioners: the $$$i$$$-th air conditioner is placed in cell $$$a_i$$$ ($$$1 \le a_i \le n$$$). Two or more air conditioners cannot be placed in the same cell (i.e. all $$$a_i$$$ are distinct).Each air conditioner is characterized by one parameter: temperature. The $$$i$$$-th air conditioner is set to the temperature $$$t_i$$$.    Example of strip of length $$$n=6$$$, where $$$k=2$$$, $$$a=[2,5]$$$ and $$$t=[14,16]$$$. For each cell $$$i$$$ ($$$1 \le i \le n$$$) find it's temperature, that can be calculated by the formula $$$$$$\min_{1 \le j \le k}(t_j + |a_j - i|),$$$$$$where $$$|a_j - i|$$$ denotes absolute value of the difference $$$a_j - i$$$.In other words, the temperature in cell $$$i$$$ is equal to the minimum among the temperatures of air conditioners, increased by the distance from it to the cell $$$i$$$.Let's look at an example. Consider that $$$n=6, k=2$$$, the first air conditioner is placed in cell $$$a_1=2$$$ and is set to the temperature $$$t_1=14$$$ and the second air conditioner is placed in cell $$$a_2=5$$$ and is set to the temperature $$$t_2=16$$$. In that case temperatures in cells are:  temperature in cell $$$1$$$ is: $$$\min(14 + |2 - 1|, 16 + |5 - 1|)=\min(14 + 1, 16 + 4)=\min(15, 20)=15$$$;  temperature in cell $$$2$$$ is: $$$\min(14 + |2 - 2|, 16 + |5 - 2|)=\min(14 + 0, 16 + 3)=\min(14, 19)=14$$$;  temperature in cell $$$3$$$ is: $$$\min(14 + |2 - 3|, 16 + |5 - 3|)=\min(14 + 1, 16 + 2)=\min(15, 18)=15$$$;  temperature in cell $$$4$$$ is: $$$\min(14 + |2 - 4|, 16 + |5 - 4|)=\min(14 + 2, 16 + 1)=\min(16, 17)=16$$$;  temperature in cell $$$5$$$ is: $$$\min(14 + |2 - 5|, 16 + |5 - 5|)=\min(14 + 3, 16 + 0)=\min(17, 16)=16$$$;  temperature in cell $$$6$$$ is: $$$\min(14 + |2 - 6|, 16 + |5 - 6|)=\min(14 + 4, 16 + 1)=\min(18, 17)=17$$$. For each cell from $$$1$$$ to $$$n$$$ find the temperature in it.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases in the input. Then test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains two integers $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) and $$$k$$$ ($$$1 \le k \le n$$$) — the length of the strip of land and the number of air conditioners respectively. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$) — positions of air conditioners on the strip of land. The third line contains $$$k$$$ integers $$$t_1, t_2, \ldots, t_k$$$ ($$$1 \le t_i \le 10^9$$$) — temperatures of air conditioners. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case output $$$n$$$ integers separated by space: temperatures of air in cells.

t = gets.chomp.to_i
t.times do
  gets
  n, _ = gets.chomp.split(' ').map(&:to_i)
  pos = gets.chomp.split(' ').map(&:to_i)
  temp = gets.chomp.split(' ').map(&:to_i)

  ans_l = ans_r = Array.new(n+1) { 10**10 }
  pos.zip(temp).each do |p, t|
    ans_l[p] = ans_r[p] = t
  end

  2.upto n do |i|
    ans_l[i] = [ans_l[i], ans_l[i-1] + 1].min
  end

  (n-1).downto 1 do |i|
    ans_r[i] = [ans_r[i], ans_r[i+1] + 1].min
  end

  ans = ans_l.zip(ans_r).map { |a, b| [a,b].min }
  puts "#{ans[1..].join(' ')}\n"
end


You are given two positive integers $$$a$$$ and $$$b$$$.In one move, you can change $$$a$$$ in the following way:  Choose any positive odd integer $$$x$$$ ($$$x > 0$$$) and replace $$$a$$$ with $$$a+x$$$;  choose any positive even integer $$$y$$$ ($$$y > 0$$$) and replace $$$a$$$ with $$$a-y$$$. You can perform as many such operations as you want. You can choose the same numbers $$$x$$$ and $$$y$$$ in different moves.Your task is to find the minimum number of moves required to obtain $$$b$$$ from $$$a$$$. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is given as two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case, print the answer — the minimum number of moves required to obtain $$$b$$$ from $$$a$$$ if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain $$$b$$$ from $$$a$$$.

NoteIn the first test case, you can just add $$$1$$$.In the second test case, you don't need to do anything.In the third test case, you can add $$$1$$$ two times.In the fourth test case, you can subtract $$$4$$$ and add $$$1$$$.In the fifth test case, you can just subtract $$$6$$$.

# cook your code here
t = gets.to_i
until t == 0
    t-=1
    x,y = gets.chomp.split().map { |e| e.to_i }
    if(x == y)
        puts "0"
    elsif(x > y)
        if((x-y)%2 == 0)
            puts "1"
        else
            puts "2"
        end
    else
        if((y-x)%2 == 1)
            puts "1"
        else
            puts "2"
        end
    end
end

t = gets.chomp.to_i

until t==0
    t-=1
    x, y = gets.split.map(&:to_i)
    if(x>y && (x-y)%2!=0)
        puts 2
    elsif(x>y && (x-y)%2==0)
        puts 1
    elsif(x<y && (y-x)%2==0)
        puts 2
    elsif(x<y && (y-x)%2!=0)
        puts 1
    end
    if(x==y)
        puts 0
    end

end

t = gets.to_i

while t > 0
  k = gets.split(" ")
  a = k[0].to_i
  b = k[1].to_i

  if a == b
    puts 0
  elsif a > b
    if a % 2 != b % 2
      puts 2
    else
      puts 1
    end
  else
    if a % 2 != b % 2
      puts 1
    else
      puts 2
    end
  end
  t -= 1
end

require 'set'; require 'prime'
INF=Float::INFINITY; MOD=10**9+7
t = gets.chomp.to_i
t.times do
  a,b = gets.chomp.split.map(&:to_i)
  if a < b
    if (b-a).odd?
      puts 1
    else
      puts 2
    end
  elsif a > b
    if (a-b).even?
      puts 1
    else
      puts 2
    end
  else
    puts 0
  end
end

N = gets.to_i
N.times do
    a,b = gets.split.map(&:to_i)
    f = b - a;
    ans = 0
    if f == 0
        ans = 0
    elsif f<0 && f.odd?
        ans = 2
    elsif f<0 && f.even?
        ans = 1
    elsif f>0 && f.odd?
        ans = 1
    elsif f>0 && f.even?
        ans = 2
    end
    puts ans
end

n=gets.to_i
(1..n).each do |x|
  a,b=gets.chomp.split(" ").map(&:to_i)
  if a == b
    print("0\n")
  elsif a > b && (a - b) % 2 == 0
  	print("1\n")
  elsif a > b && (a - b) % 2 == 1
  	print("2\n")
  elsif a < b && (b - a) % 2 == 0
  	print("2\n")
  elsif a < b && (b - a) % 2 == 1
  	print("1\n")
  end
end

gets.to_i.times {
  a, b = gets.split.map { |v| v.to_i }

  if a == b
    puts 0
  elsif a < b
    puts 2 - (b - a) % 2
  else
    puts 1 + (b - a) % 2
  end
}

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

n = gets.to_i
n.times {
  a, b = gli

  if a < b
    if (a - b) % 2 == 1
      puts 1
    else
      puts 2
    end
  elsif a == b
    puts 0
  else
    if (b - a) % 2 == 1
      puts 2
    else
      puts 1
    end
  end
}

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

n = gets.to_i

n.times do |l|
    a, b = input_line
    if a == b then
        puts 0
    elsif a > b
        puts (b - a).even? ? 1 : 2
    else
        puts (a - b).even? ? 2 : 1
    end
end

gets.to_i.times do
  a, b = gets.split.map &:to_i
  d = a - b
  if d == 0
    puts 0
  elsif d%2 == 0
    puts d > 0 ? 1 : 2
  else
    puts d < 0 ? 1 : 2
  end
end

1.upto(gets.to_i) do
  a, b = gets.split(' ').map(&:to_i)
  result = (b-a).zero? ? 0 : 2 - (b-a).modulo(2)

  result = 3 - result if (b - a) < 0

  puts result
end

t = gets.to_i
(1).upto(t) do
  a = gets.split(' ').map(&:to_i)
  answer = 2
  if(a[0]<a[1] and (a[0]-a[1]).modulo(2) == 1) or (a[0]>a[1] and (a[0]-a[1]).modulo(2) == 0)
    answer=1
  elsif a[0]==a[1]
    answer=0
  end
  puts answer
end


Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 1) — the i-th row of the matrix a.

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001

#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')
#$stdout.reopen('/home/chen/Desktop/output.txt', 'w')

def min(a)
	f = 1
	s = 0
	a.each do |e|
		if f
			s=e
			f=0
		else
			s=e if e < s
		end
	end
	s
end

def solve(ib,ie,j,a)
	if (ie-ib+1)%2 !=0
		return 0
	end
	b ,e = ib, ie
	while e>b
		if a[e][j] != a[b][j]
			return 0
		end
		b+=1
		e-=1
	end

	return solve(ib, (ib+ie)/2,j,a)+1
end

n,m = gets.split.map(&:to_i)
a = [0]*n
ans = [0]*m

(1..n).each do |i|
	a[i-1] = gets.split.map(&:to_i)
end

(0..ans.size-1).each do |i|
	ans[i] = solve(0,n-1,i,a)
end

puts n/(2**min(ans))

def run
  n, m = $stdin.gets.split.map(&:to_i)
  a = []
  n.times do |i|
    a << $stdin.gets.chomp
  end

  ans = n
  flag = true
  cur = n
  while flag
    if cur % 2 == 0
      cur = cur / 2
    else
      ans = cur
      break
    end

    cur.times do |i|
      if a[i] != a[cur * 2 - 1 - i]
        flag = false
        ans = cur * 2
        break
      end
    end
  end

  puts ans
end

run if $0 == __FILE__


Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e.  or  (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.

If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.

NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.

require 'set'

n, m = gets.split.map(&:to_i)
adj = Array.new(n){[]}
m.times do
  u, v = gets.split.map{|s| s.to_i-1}
  adj[u] << v
  adj[v] << u
end

rem = (0...n).to_set
sides = Array.new(n)
while rem.any?
  v = rem.first
  rem.delete v
  sides[v] = 0
  q = [v]
  while q.any?
    v = q.shift
    side = sides[v];
    adj[v].each do |s|
      if not sides[s]
        newside = (side + 1) % 2
        sides[s] = newside
        q << s
        rem.delete s
      else
        if sides[s] == side
          puts -1
          exit
        end
      end
    end
  end
end

sides.each_with_index.group_by(&:first).values.each do |vs|
  puts vs.size
  puts vs.map(&:last).map{|v| v+1}.join(" ")
end


There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.  Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.

f = File.open("input.txt", "r")
s = f.read.split
n = s[0].to_i
m = s[1].to_i
f.close

if n > m then
    s = "BG"*m + "B"*(n-m)
else
    s = "GB"*n + "G"*(m-n)
end

f = File.open("output.txt", "w")
f.write(s)
f.close
puts s

#!/usr/bin/ruby
f=nil
if true
	f=File.open('input.txt','rb')
else
	f=$<
end
b,g=f.gets.split.map(&:to_i)
m=[b,g].min
b-=m;g-=m
p [g,m,b]
File.write('output.txt','G'*g+'BG'*m+'B'*b)

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
input=gets.to_s.split
n = input[0].to_i
m = input[1].to_i
str = ""
if n==m
	n.times{str+="BG"}
elsif n > m
	m.times{str+="BG"}
	(n-m).times{str+="B"}
else
	n.times{str+="GB"}
	(m-n).times{str+="G"}
end
puts str

$stdin=File.open('input.txt')
$stdout=File.open('output.txt', 'w')
n,m=gets.split.map(&:to_i)
m>=n ? (print "GB"*[m,n].min; print "G"*(m-n) if n<m) : (print "BG"*[m,n].min; print "B"*(n-m) if n>m)

$stdin=File.open('input.txt')
$stdout=File.open('output.txt', 'w')
n,m=gets.split.map(&:to_i)
print "GB"*[m,n].min if m>=n
 print "BG"*[m,n].min if m<n
print "B"*(n-m) if n>m
print "G"*(m-n) if n<m

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

$stdin = File.open("input.txt")
$stdout = File.open("output.txt", "w")

n, m = gets.chomp.split(" ").map{|n| n.to_i}

if n == m
  puts "GB" * n
elsif n > m
  puts "BG" * m + "B" * (n - m)
else
  puts "GB" * n + "G" * (m - n)
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
n, m = gets.split.map(&:to_i)
puts (n <= m ? "GB" : "BG")*[n, m].min + (n <= m ? "G" : "B")*([n,m].max-[n,m].min)

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a=gets.chomp.split(" ")
b=a[0].to_i
g=a[1].to_i
ans=""
if b>=g
loop do
break if b==0 && g==0
if b!=0
ans+="B"
b-=1
end
if g!=0
ans+="G"
g-=1
end
end
else
loop do
break if b==0 && g==0
if g!=0
ans+="G"
g-=1
end
if b!=0
ans+="B"
b-=1
end
end
end

puts "#{ans}"

n,m=File.open("input.txt").gets.split.map(&:to_i)
File.open("output.txt", "w") { |f|
	if n < m then
		f.puts "GB"*n + "G"*(m-n)
	else
		f.puts "BG"*m + "B"*(n-m)
	end
}

m, n= File.open("input.txt").gets.split.map(&:to_i)
File.open("output.txt", "w") { |f|
  if m > n
    f.puts 'BG'*n + 'B'*(m-n)
  else
    f.puts 'GB'*m + 'G'*(n-m)
  end
}

a=[]
File.open("input.txt","r") do |file|
  a=file.gets.chomp.split
end

n=a[0].to_i
m=a[1].to_i

if(n>m)
 maxc='B'
 minc='G'
 mini=m
else
 maxc='G'
 minc='B'
 mini=n
end

a=""

(n+m).times do
 a+=maxc
end

ind=1
mini.times do
 a[ind]=minc
 ind+=2
end
File.open("output.txt","w") do |file|
  file.puts a
end

n, m = 0, 0
File.open("input.txt", "r") do |file|
    n, m = file.gets.split.collect{|i| i.to_i}
end
File.open("output.txt", "w") do |file|
    if n >= m
        file.puts (['B','G']*m+['B']*(n-m)).join
    else
        file.puts (['G','B']*n+['G']*(m-n)).join
    end
end

#n, m = IO.readlines("input.txt")[0].split.collect{|i| i.to_i}
n, m = File.new("input.txt", "r").gets.split.collect{|i| i.to_i}
if n >= m
    File.new("output.txt", "w").puts (['B','G']*m+['B']*(n-m)).join
else
    File.new("output.txt", "w").puts (['G','B']*n+['G']*(m-n)).join
end

file = File.new("input.txt", "r")
n, m = file.gets.split.collect{|i| i.to_i}
file.close
file = File.new("output.txt", "w")
if n >= m
    file.puts (['B','G']*m+['B']*(n-m)).join
else
    file.puts (['G','B']*n+['G']*(m-n)).join
end
file.close

file = File.open('input.txt', "r")
n, m = file.gets.split.map { |x| x.to_i }
file.close

File.open('output.txt', 'w') { |f| f.write(n == m ? 'GB' * n : n > m ? 'BG' * m + 'B' * (n - m) : 'GB' * n + 'G' * (m - n)) }

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a = gets.split.map(&:to_i)

if a[0] == a[1]
    a[0].times do
        print "BG"
    end
    exit
end
p=a[0]-a[1]
r=a[1]-a[0]
if a[0]>a[1]
    a[1].times do
        print "BG"
    end
    p.times do
         print "B"
    end
    exit
end

if a[1]>a[0]
    a[0].times do
        print "GB"
    end
    r.times do
         print "G"
    end
    exit
end

n, m = File.open("input.txt").gets.split.map(&:to_i)
output = File.open("output.txt", "w")
while n > 0 || m > 0
	if (n >= m)
		output.print 'B'
		output.print 'G' if m > 0
	else
		output.print 'G'
		output.print 'B' if n > 0
	end
	n, m = n - 1, m - 1
end

input = File.new('input.txt', 'r')
output = File.new('output.txt', 'w')

t = input.gets.split.collect { |e| e.to_i  }

n,m = t[0], t[1]

f,l = 'B','G'
if n < m
	f,l = 'G','B'
end
min = t.min
others = t.max - min

for i in 1..min do
	output.print f,l
end
for i in 1..others do
	output.print f
end

input.close
output.close

f = File.open("input.txt", "r")
s = f.read.split
n = s[0].to_i
m = s[1].to_i
f.close

if n > m then
    s = "BG"*m + "B"*(n-m)
else
    s = "GB"*n + "B"*(m-n)
end

f = File.open("output.txt", "w")
f.write(s)
f.close
puts s

#!/usr/bin/ruby
f=nil
if true
	f=File.open('input.txt','rb')
else
	f=$<
end
b,g=f.gets.split.map(&:to_i)
m=[b,g].min
b-=m;g-=m
p [g,m,b]
puts 'G'*g+'BG'*m+'B'*b

#!/usr/bin/ruby
f=nil
if true
	f=File.open('input.txt','rb')
else
	f=$<
end
b,g=f.gets.split.map(&:to_i)
m=[b,g].min
b-=m;g-=m
puts 'G'*g+'BG'*m+'B'*b

#!/usr/bin/ruby
$stdin=File.open('input.txt','rb')
b,g=gets.split.map(&:to_i)
m=[b,g].min
b-=m;g-=m
puts 'G'*g+'BG'*m+'B'*b

$stdin=File.open('input.txt')
$stdout=File.open('output.txt', 'w')
n,m=gets.split.map(&:to_i)
print "GB"*[m,n].min if m>=n
 print "BG"*[m,n].min if m<n
print "B"*m if n>m
print "G"*m if n<m

$stdin=File.open('input.txt')
$stdout=File.open('output.txt', 'w')
n,m=gets.split.map(&:to_i)
print "GB"*[m,n].min
print "B"*m if n>m
print "G"*m if n<m

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a=gets.chomp.split(" ")
b=a[0].to_i
g=a[1].to_i
ans=""
if b>=g
loop do
break if b==0 && g==0

if b!=0
ans+="B"
b-=1
end

if g!=0
ans+="G"
g-=1
end

end
else
loop do
break if b==0 && g==0

if b!=0
ans+="B"
b-=1
end

if g!=0
ans+="G"
g-=1
end

end
end

puts "#{ans}"

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a=gets.chomp.split(" ")
b=a[0].to_i
g=a[1].to_i
ans=""

loop do
break if b==0 && g==0

if b!=0
ans+="B"
b-=1
end

if g!=0
ans+="G"
g-=1
end

end

puts "#{ans}"

m, n= File.open("input.txt").gets.split.map(&:to_i)
File.open("output.txt", "w") { |f|
  if m > n
    f.puts 'BG'*n + 'B'*(m-n)
  else
    f.puts 'GB'*n + 'G'*(n-m)
  end
}

n, m = IO.readlines("input.txt")[0].split.collect{|i| i.to_i}
if n >= m
    puts (['B','G']*m+['B']*(n-m)).join
else
    puts (['G','B']*n+['G']*(m-n)).join
end

b=gets.to_i
g=gets.to_i
if b == g
    b.times do
        puts "BG"
    end
end

if b>g
    g.times do
        puts "BG"
    end
    b-g.times do
         puts "B"
    end
end

if g>b
    b.times do
        puts "GB"
    end
    g-b.times do
         puts "G"
    end
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a = gets.split.map(&:to_i)

if a[0] == a[1]
    a[0].times do
        print "BG"
    end
    exit
end

if a[0]>a[1]
    a[1].times do
        print "BG"
    end
    a[0]-a[1].times do
         print "B"
    end
    exit
end

if a[0]>a[1]
    a[1].times do
        print "GB"
    end
    a[1]-a[0].times do
         print "G"
    end
    exit
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a = gets.split.map(&:to_i)
if a[0] == a[1]
    a[0].times do
        print "BG"
    end
end

if a[0]>a[1]
    a[1].times do
        print "BG"
    end
    a[0]-a[1].times do
         print "B"
    end
end

if a[0]>a[1]
    a[1].times do
        print "GB"
    end
    a[1]-a[0].times do
         print "G"
    end
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a = gets.split.map(&:to_i)

if a[0] == a[1]
    a[0].times do
        print "BG"
    end
    exit
end

if a[0]>a[1]
    a[0].times do
        print "BG"
    end
    a[0]-a[1].times do
         print "B"
    end
    exit
end

if a[0]>a[1]
    a[1].times do
        print "GB"
    end
    a[1]-a[0].times do
         print "G"
    end
    exit
end

$stdin=File.open('input.txt')
$stdout=File.open('output.txt','w')
a = gets.split.map(&:to_i)

if a[0] == a[1]
    a[0].times do
        print "BG"
    end
    exit
end

if a[0]>a[1]
    a[1].times do
        print "BG"
    end
    a[0]-a[1].times do
         print "B"
    end
    exit
end

if a[1]>a[0]
    a[0].times do
        print "GB"
    end
    a[1]-a[0].times do
         print "G"
    end
    exit
end


The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.

The first line of input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \leq x_0 \leq 10^{14}$$$) and $$$n$$$ ($$$0 \leq n \leq 10^{14}$$$) — the coordinate of the grasshopper's initial position and the number of jumps.

Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer — the answer to the $$$i$$$-th test case — the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$.

NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$.

t = gets.to_i
t.times do
    x0, n = gets.split.map(&:to_i)
    x = x0
    m = n / 4 * 4 + 1
    (m .. n).each do |i|
        if x.odd?
            x += i
        else
            x -= i
        end
    end
    puts x
end

gets.to_i.times do
  x,n=gets.split.map(&:to_i)
  if n%4==0
    puts x
  elsif n%4==1
    if x.even?
      puts x-n
    else
      puts x+n
    end
  elsif n%4==2
    if x.even?
      puts x+1
    else
      puts x-1
    end
  else
    if x.even?
      puts x+n+1
    else
      puts x-n-1
    end
  end
end


And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then — to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti.

The first line contains two space-separated integers n and m (1 ≤ n ≤ 105, 2 ≤ m ≤ 108).  Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1 ≤ si, fi ≤ m, 0 ≤ ti ≤ 108), described in the problem statement.

Print n lines each containing one integer — the time of the arrival for each participant to the required floor.

NoteLet's consider the first sample. The first participant starts at floor s = 2 by the time equal to t = 3. To get to the floor f = 4, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t = 0 on the floor s = 1, enters the elevator immediately, and arrives to the floor f = 2. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts.

# -*- coding: utf-8 -*-

def hoge(s,f,t,m)
  return t if s==f
  p=(m-1)*2
  base= (t/p)*p
  t -= base
  base + if s < f
    #up
    if t<=s-1
      f-1
    else
      p+f-1
    end
  else
    #down
    if t<=p-s+1
      p-f+1
    else
      p-f+1 + p
    end
  end
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  r = hoge(s,f,t,m)
  puts r
}

# -*- coding: utf-8 -*-
def f(s,f,t,m)
  return t if s==f
  p=(m-1)*2
  base= (t/p)*p
  ont = [base+s-1,base+p-s+1,base+s-1+p,base+p-s+1+p].find{|i| i>=t}
  [base+f-1,base+p-f+1,base+f-1+p,base+p-f+1+p].find{ |i| i>=ont}
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  puts f(s,f,t,m)
}

n,m=gets.split.map(&:to_i)
p=(m-1)*2
n.times {
  s,f,t=gets.split.map(&:to_i)
  if s==f
    puts t
  else
    base= (t/p)*p
    ont = [base+s-1,base+p-s+1,base+s-1+p,base+p-s+1+p].find{|i| i>=t}
    puts [base+f-1,base+p-f+1,base+f-1+p,base+p-f+1+p].find{ |i| i>=ont}
  end
}

def calctime(m, s, f, t)
  if s < f
    wk = s - 1
  else
    wk = (m-1) + (m-s)
  end
  while true
    break if t <= wk
    wk += (m-1)*2
  end
  return wk + (s-f).abs
end
n, m = gets.chomp.split(/ /).map!{|x| x.to_i}
for i in 0..n-1
  s,f,t = gets.chomp.split(/ /).map!{|x| x.to_i}
  ret = t
  if s != f
    ret = calctime(m,s,f,t)
  end
  puts ret
end

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts t
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

def solve
  n, m = gets.strip.split(' ').map(&:to_i)
  m -= 1
  n.times do
    s, f, t = gets.strip.split(' ').map(&:to_i)
    r = nil
    s -= 1
    f -= 1
    if s == f
      r = t
    elsif s < f
      r = s
      while r < t
        r += 2 * m
      end
      r += (f-s).abs
    else
      r = 2 * m - s
      while r < t
        r += 2 * m
      end
      r += (f-s).abs
    end
    puts r
  end
end

solve

def solve(s, f, t, m)
  lapse = 2 * (m - 1)

  # if a person is already at his destination
  # then we just return the time when he start waiting
  return t if s == f

  if s < f
    ret = s - 1
    ret += ((t - ret) / lapse.to_f).ceil * lapse if ret < t
    # same as this
    # while ret < t
    #   ret += lapse
    # end
    ret += f - s
  else
    ret = lapse - (s - 1)
    ret += ((t - ret) / lapse.to_f).ceil * lapse if ret < t
    # same as this
    # while ret < t
    #   ret += lapse
    # end
    ret += s - f
  end
  ret
end

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

n.times do
  s, f, t = gets.strip.split(' ').map(&:to_i)
  puts solve(s, f, t, m)
end

def solve(s, f, t, m)
  lapse = 2 * (m - 1)
  # if a person is already at his destination
  # then we just return the time when he start waiting
  return t if s == f

  if s < f
    ret = s - 1
    while ret < t
      ret += lapse
    end
    ret += f - s
  else
    ret = lapse - (s - 1)
    while ret < t
      ret += lapse
    end
    ret += s - f
  end
  ret
end

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

n.times do
  s, f, t = gets.strip.split(' ').map(&:to_i)
  puts solve(s, f, t, m)
end

def read_next_line
  gets.split.map { |x| x.to_i }
end

n, m = read_next_line
q = 2 * m
z = m - 1
k = 2 * z
for _ in 1..n
  s, f, t = read_next_line
  if s == f
    puts t
    next
  end
  r = t % k
  es = m - (z - r).abs
  d = r > z
  pt = es == s ? 0 : d ^ (es < s) ? (s - es).abs : (d ^= 1) ? q - (s + es) : (s + es) - 2
  pt += d ^ (f > s) ? (s -f).abs : d ? (s + f) - 2 : q - (s + f)
  puts t + pt
end

# -*- coding: utf-8 -*-

def hoge(s,f,t,m)
  return 0 if s==f
  p=(m-1)*2
  base= (t/p)*p
  t -= base
  base + if s < f
    #up
    if t<=s-1
      f-1
    else
      p+f-1
    end
  else
    #down
    if t<=p-s+1
      p-f+1
    else
      p-f+1 + p
    end
  end
end

n,m=gets.split.map(&:to_i)
n.times {
  s,f,t=gets.split.map(&:to_i)
  r = hoge(s,f,t,m)
  puts r
}

def calctime(m, s, f, t)
  if s < f
    wk = s - 1
  else
    wk = (m-1) + (m-s)
  end
  while true
    break if t <= wk
    wk += (m-1)*2
  end
  return wk + (s-f).abs
end
n, m = gets.chomp.split(/ /).map!{|x| x.to_i}
for i in 0..n-1
  ret = 0
  s,f,t = gets.chomp.split(/ /).map!{|x| x.to_i}
  if s != f
    ret = calctime(m,s,f,t)
  end
  puts ret
end

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

input=gets.split.map(&:to_i)
n=input[0]
m=input[1]-1
n.times{
        input=gets.split.map(&:to_i)
        s=input[0]-1
        f=input[1]-1
        t=input[2]
        if s==f then
                puts 0
        elsif s<f then
                #登り
                tt=t%(2*m)
                cnt=t/(2*m)
                if tt>s then
                        cnt+=1
                end
                puts cnt*2*m+f
        else
                tt=t%(2*m)
                cnt=t/(2*m)
                s,f=f,s
                if tt>m-f+m then
                        cnt+=1
                end
                puts cnt*2*m+m+m-s
        end
}

def running(ans, max, n, k, sum)
  limit = max / ans;
  ret = 0;
  1.upto(limit) do |j|
    sum[j * ans + k] ||= 0
    sum[j * ans - 1] ||= 0
    ret += sum[j * ans + k] - sum[j * ans - 1]
  end
  return ret == n;
end

def solve
  min = Float::INFINITY
  max = 0

  n, k = gets.strip.split.map(&:to_i)
  a = []
  sum = []

  gets.strip.split.each do |x|
    x = x.to_i
    a << x
    min = [x, min].min
    max = [x, max].max
    sum[x] ||= 0
    sum[x] += 1
  end

  min.upto(max+k) do |i|
    sum[i] ||= 0
    sum[i-1] ||= 0
    sum[i] += sum[i-1]
  end

  if min <= k+1
    puts min
    return
  end
  min.downto(k+1) do |i|
    if running(i, max, n, k, sum)
      puts i
      return
    end
  end
end

solve


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

#!/usr/bin/ruby
l,*a=$<.read.split.map &:to_i
h={}
a.each{|i|
	h[i]=1
	r=[]
	while h[l]
		r<<l
		l-=1
	end
	puts r*' '
}

require 'set'
n = gets.to_i
max = n
all = []
set = Set.new
nums = gets.split(' ').map{ |i| i.to_i }

n.times do |i|
  ans = []
  set << nums[i]
  #puts set.inspect
  if nums[i] == max
    while set.include?(max)
      ans << max
      set.delete(max)
      max-=1
    end
  end
  puts ans.join(' ')
end

n=gets.chomp.to_i
snack=gets.chomp.split.map{|x| x.to_i}
state=Array.new(n+1,0);
start=n
snack.each do |x|
	state[x]=1
	i=start
	while i>0
		if state[i]==2
			start-=1
		else
			if state[i]==1
				print " #{i}"
				state[i]=2#就是说在state 2下，i糖果已经被放好！
			else
				break
			end
		end
		i-=1
	end
	puts
end

#!/usr/bin/env ruby

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

snack_back = {}

snack_days.each do |new_snack|
  if new_snack == max_size
	print new_snack
	max_size -= 1
	while snack_back[max_size]
	  print " #{max_size}"
	  max_size -= 1
	end
  else
	snack_back[new_snack] = true
  end
  print "\n"
end


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $$$2$$$) or determine that there is no such subset.Both the given array and required subset may contain equal values.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$), number of test cases to solve. Descriptions of $$$t$$$ test cases follow. A description of each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$), length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$), elements of $$$a$$$. The given array $$$a$$$ can contain equal values (duplicates).

For each test case output $$$-1$$$ if there is no such subset of elements. Otherwise output positive integer $$$k$$$, number of elements in the required subset. Then output $$$k$$$ distinct integers ($$$1 \leq p_i \leq n$$$), indexes of the chosen elements. If there are multiple solutions output any of them.

NoteThere are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is $$$4$$$ and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1323/A

count = gets.to_i

answers = []

count.times do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)

  odd_index = nil

  a.each_with_index do |num, index|
    if num % 2 == 0
      answers << 1 << index + 1
      break
    elsif n == 1
      answers << -1
      break
    else
      if odd_index.nil?
        odd_index = index + 1
      else
        answers << 2 << "#{odd_index} #{index+1}"
        break
      end
    end
  end
end

answers.each { |answer| puts answer }

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  flg = false
  n.times do |i|
    if a[i].even?
      p 1
      p i+1
      flg = true
      break
    end
  end
  next if flg
  if n == 1
    p -1
  else
    p 2
    puts "1 2"
  end
end

#! /usr/bin/env ruby
# encoding: UTF-8

def solve
n = gets.to_i
xs = gets.split.map{|x| x.to_i }
evens = n.times.select {|i| xs[i] % 2 == 0 }
odds = n.times.select {|i| xs[i] % 2 == 1 }
if evens.size > 0 then	puts 1; puts evens.first + 1; return; end
if odds.size > 1 then  puts 2; print(odds[0]+1, ' ', odds[1]+1); puts; return; end
puts -1
end

t = gets.to_i
t.times {solve}

T = gets.to_i

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

  idx = a.index { |x| x % 2 == 0 }

  if idx
    puts 1
    puts idx + 1
  else
    odds = []

    n.times do |i|
      odds << i + 1 if a[i].odd?
    end

    if odds.size >= 2
      ans = odds.take(2)
      puts ans.size
      puts ans.join(' ')
    else
      puts -1
    end
  end
end

# coding: utf-8

t = gets.to_i
t.times {
    n = gets.to_i
    ar_odds, ar_evens = [], []
    gets.split.each_with_index { |i, index|
        i = i.to_i
        index += 1 # 1-based
        if i.odd?
            ar_odds << index
        else
            ar_evens << index
        end
    }

    if ar_evens.length > 0
        puts 1
        puts ar_evens.first
    else
        if ar_odds.length == 1
            puts -1
        else
            puts 2
            puts ar_odds[0...2].join(' ')
        end
    end

}

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  even = []
  odd = []
  a.each_with_index do |v, i|
    if v % 2 == 0
      even.push(i + 1)
    else
      odd.push(i + 1)
    end
  end
  if even.length >= 1
    puts 1
    puts even[0]
  elsif odd.length >= 2
    puts 2
    puts "#{odd[0]} #{odd[1]}"
  else
    puts -1
  end
end

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1323/A

count = gets.to_i

answers = []

count.times do
  n = gets.to_i
  a = gets.split(' ').map(&:to_i)

  odd_index = nil

  a.each_with_index do |num, index|
    if n == 1
      answers << -1
      break
    end
    if num % 2 == 0
      answers << 1 << index + 1
      break
    else
      if odd_index.nil?
        odd_index = index + 1
      else
        answers << 2 << "#{odd_index} #{index+1}"
        break
      end
    end
  end
end

answers.each { |answer| puts answer }

t = gets.to_i
t.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  flg = false
  n.times do |i|
    if a[i].even?
      p 1
      p i+1
      flg = true
    end
  end
  next if flg
  if n == 1
    p -1
  else
    p 2
    puts "1 2"
  end
end


Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains $$$a$$$ stones, the second of them contains $$$b$$$ stones and the third of them contains $$$c$$$ stones.Each time she can do one of two operations:  take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);  take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $$$0$$$ stones. Can you help her?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. Next $$$t$$$ lines describe test cases in the following format: Line contains three non-negative integers $$$a$$$, $$$b$$$ and $$$c$$$, separated by spaces ($$$0 \leq a,b,c \leq 100$$$) — the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

Print $$$t$$$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations.

NoteFor the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $$$9$$$. It is impossible to make some operations to take more than $$$9$$$ stones, so the answer is $$$9$$$.

T = gets.to_i
T.times do
  a,b,c = gets.split.map(&:to_i)
  ans = 0
  (a+1).times do |i|
    x = [a,b/2,i].min
    d,e,f = a-x, b-x*2, c
    sum = x*3
    while e > 0 && f > 1
      sum += 3
      e -= 1
      f -= 2
    end
    ans = [ans, sum].max
  end
  p ans
end

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)

  ans1 = 0
  t = [b, c/2].min
  b -= t
  c -= t * 2
  ans1 += t * 3
  t = [a, b/2].min
  a -= t
  b -= t * 2
  ans1 += t * 3

  ans2 = 0
  t = [a, b/2].min
  a -= t
  b -= t * 2
  ans2 += t * 3
  t = [b, c/2].min
  b -= t
  c -= t * 2
  ans2 += t * 3

  puts [ans1, ans2].max
end

vals = STDIN.readlines
n = vals[0].to_i
stones = []
n.times { |i|
  s = vals[i + 1].split(' ').map(&:to_i)
  stones.push(s)
}
stones.each { |stone|
  ret = 0
  while stone[2] > 1 && stone[1] >= 1
    stone[2] = stone[2] - 2
    stone[1] = stone[1] - 1
    ret += 3
  end
  while stone[1] > 1 && stone[0] >= 1
    stone[1] = stone[1] - 2
    stone[0] = stone[0] - 1
    ret += 3
  end
  p ret
}

def calcs(x,y,ax,ay,bx,by) ((ax-x)*(by-y)-(bx-x)*(ay-y))/2.0 end

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaizyo(n)(n < 2)? 1 : (2..n).inject(:*) end

def scount(a) b=na(a.max+1);a.each{|n|b[n]+=1};return b end

def na(n=0,d=0) Array.new(n,d)end

def na2(n=0,m=0,d=0) Array.new(n){Array.new(m,d)}end

def na3(n=0,m=0,l=0,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def bit(n) n.to_s(2).split("").map(&:to_i) end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

n = inp[0]
ans = 0
n.times do |i|
  t = inp
  f = [t[2]/2,t[1]].min
  t[1] -= f
  s = [t[0],t[1]/2].min
  p (f+s)*3
end

MOD=10**9+7
cnt=0; sum=0; prev=nil; can=true; h=Hash.new(0)
def gs() gets.chomp end
def gi() gets.to_i end
def gsmi() gets.chomp.split.map(&:to_i) end

def desc(ar) ar.sort!{|x,y|y<=>x} end
def min(a,b) a<=b ? a : b end
def max(a,b) a>=b ? a : b end
def sum(ar) ar.inject(:+) end

#def bs(ar,eq,n) en=(eq==1 ? :>= : :>); ar.bsearch_index{|x|x.send(en,n)} end
def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########

t=gi
ans=[]
t.times do
  a,b,c=gsmi
  c1=min(c/2,b)
  cnt=c1
  b=b-c1
  c2=min(b/2,a)
  cnt+=c2
  ans<<cnt*3
end
puts ans

t = gets.to_i
t.times do
  a, b, c = gets.split.map &:to_i
  s = [b, c/2].min
  f = [a, (b - s)/2].min
  puts (f + s)*3
end

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  ans = 0
  if b < c
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
  else
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
  end
  puts ans
end

gets.to_i.times do
  a, b, c = gets.split.map(&:to_i)
  ans = 0
  if b <= c
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
  else
    t = [a, b/2].min
    a -= t
    b -= t * 2
    ans += t * 3
    t = [b, c/2].min
    b -= t
    c -= t * 2
    ans += t * 3
  end
  puts ans
end

vals = STDIN.readlines
n = vals[0].to_i
stones = []
n.times { |i|
  s = vals[i + 1].split(' ').map(&:to_i)
  stones.push(s)
}
stones.each { |stone|
  ret = 0
  while stone[2] > 1 && stone[1] > 1
    stone[2] = stone[2] - 2
    stone[1] = stone[1] - 1
    ret += 3
  end
  while stone[1] > 1 && stone[0] > 1
    stone[1] = stone[1] - 2
    stone[0] = stone[0] - 1
    ret += 3
  end
  p ret
}


A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.

The first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.

For each test case, output the minimum number of 2050-numbers in one line.  If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead.

test_cases = gets.chomp.to_i
for i in 1..test_cases do
    n = gets.chomp.to_i
    if (n % 2050 == 0)
        n /= 2050
        s = n.to_s
        ans = 0
        for j in 0..s.size - 1 do
            ans += s[j].ord - '0'.ord
        end
        puts ans
    else
        puts -1
    end
end

def solution(n)
  min_number = 0
  k = 0

  while twenty_fifty_number(k) <= n
    k += 1
  end

  while k >= 0
    if n < twenty_fifty_number(k)
      k -= 1
    else
      n = n - twenty_fifty_number(k)
      min_number += 1
    end
  end

  if n == 0
    min_number
  else
    - 1
  end
end

def twenty_fifty_number(k)
  2050 * (10 ** k)
end

test_cases = gets.to_i

test_cases.times do |test_case|
  n = gets.to_i
  res = solution(n)

  puts res
end

t = gets.to_s.to_i
1.upto(t) do |casenum|
  n = gets.to_s.to_i
  if n % 2050 != 0
    printf("-1\n")
    next
  end

  n /= 2050
  res = 0
  while n > 0
    res += n % 10
    n /= 10
  end

  printf("%d\n", res)
end


George is a cat, so he really likes to play. Most of all he likes to play with his array of positive integers b. During the game, George modifies the array by using special changes. Let's mark George's current array as b1, b2, ..., b|b| (record |b| denotes the current length of the array). Then one change is a sequence of actions:   Choose two distinct indexes i and j (1 ≤ i, j ≤ |b|; i ≠ j), such that bi ≥ bj.  Get number v = concat(bi, bj), where concat(x, y) is a number obtained by adding number y to the end of the decimal record of number x. For example, concat(500, 10) = 50010, concat(2, 2) = 22.  Add number v to the end of the array. The length of the array will increase by one.  Remove from the array numbers with indexes i and j. The length of the array will decrease by two, and elements of the array will become re-numbered from 1 to current length of the array. George played for a long time with his array b and received from array b an array consisting of exactly one number p. Now George wants to know: what is the maximum number of elements array b could contain originally? Help him find this number. Note that originally the array could contain only positive integers.

The first line of the input contains a single integer p (1 ≤ p < 10100000). It is guaranteed that number p doesn't contain any leading zeroes.

Print an integer — the maximum number of elements array b could contain originally.

NoteLet's consider the test examples:   Originally array b can be equal to {5, 9, 5, 5}. The sequence of George's changes could have been: {5, 9, 5, 5} → {5, 5, 95} → {95, 55} → {9555}.  Originally array b could be equal to {1000000000, 5}. Please note that the array b cannot contain zeros.  Originally array b could be equal to {800, 10, 1}.  Originally array b could be equal to {45}. It cannot be equal to {4, 5}, because George can get only array {54} from this array in one operation. Note that the numbers can be very large.

s = ARGF.read().chomp!
l, r = 0, s.size-1
ans = 0
while l < r
  ans += 1
  m = r
  m -= 1 while l<m && s[m]=='0'
  if l<m && (l+r+1<2*m || (l+r+1==2*m && s[l]>=s[m])) then r = m-1
  else break end
end
puts ans


Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a marker is considered to be beautifully closed, if the cap color and the marker color match, that is, aj = xi.Find the way to close the maximum number of markers. If there are several such ways, then choose the one that has the maximum number of beautifully closed markers.

The first input line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of markers and the number of caps, correspondingly.  Next n lines describe the markers. The i-th line contains two space-separated integers xi, yi (1 ≤ xi, yi ≤ 1000) — the i-th marker's color and diameter, correspondingly. Next m lines describe the caps. The j-th line contains two space-separated integers aj, bj (1 ≤ aj, bj ≤ 1000) — the color and diameter of the j-th cap, correspondingly.

Print two space-separated integers u, v, where u is the number of closed markers and v is the number of beautifully closed markers in the sought optimal way. Remember that you have to find the way to close the maximum number of markers, and if there are several such ways, you should choose the one where the number of beautifully closed markers is maximum.

NoteIn the first test sample the first marker should be closed by the fourth cap, the second marker should be closed by the first cap and the third marker should be closed by the second cap. Thus, three markers will be closed, and two of them will be beautifully closed — the first and the third markers.

n,m = gets.split.map(&:to_i)
a = Hash.new
a.default = 0
b = Hash.new
b.default = 0
c = Hash.new
c.default = 0
d = Hash.new
d.default = 0

n.times{
        tmp = gets.split.map(&:to_i)
        a[tmp[1]] += 1
        b[tmp] += 1
}
m.times{
        tmp = gets.split.map(&:to_i)
        c[tmp[1]] += 1
        d[tmp] += 1
}
u,v = 0,0

a.each{|x,y|
        u += [y, c[x]].min
}

b.each{|x,y|
        v += [y, d[x]].min
}

p u
p v

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    done << _
    beautiful += 1
    closed += 1
    h.delete m[0] if a.empty?
  end
end

done.each{|i| markers[i] = nil }

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first) && a[1].shift
    closed += 1
    h.delete a[0] if a[1].empty?
  end
end

puts "#{closed} #{beautiful}"

n,m=gets.split.map(&:to_i)
markers = {}
n.times{
  color,diameter = gets.split.map(&:to_i)
  markers[diameter] ||= {}
  markers[diameter][color] ||= 0
  markers[diameter][color] += 1
}

unused_caps = {}
beautiful_closed = 0

m.times do
  color,diameter = gets.split.map(&:to_i)
  if markers[diameter] and markers[diameter][color] and markers[diameter][color] > 0
    beautiful_closed += 1
    markers[diameter][color] -= 1
  else
    unused_caps[diameter] ||= 0
    unused_caps[diameter] += 1
  end
end

closed = beautiful_closed
open_markers = {}
markers.each{|diameter,hsh|
  open_markers[diameter]=hsh.inject(0){|s,(k,v)| s+v}
}
unused_caps.each{|diameter, number|
  closed += [open_markers[diameter] || 0, unused_caps[diameter] || 0].min
}

puts "#{closed} #{beautiful_closed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}

c1h=arr[a[0]...(a[0]+a[1])].inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
m1h=arr[0...a[0]].inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
bclosed=0
c1h.each do |k,v|
  next unless m1h[k]
  bclosed+=m1h[k] >= v ? v : m1h[k]
end
c2h=arr[a[0]...(a[0]+a[1])].map{|v| v[1]}.inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
m2h=arr[0...a[0]].map{|v| v[1]}.inject(Hash.new(0)) {|h, e| h.tap {|h| h[e] += 1} }
closed=0
c2h.each do |k,v|
  next unless m2h[k]
  closed+=m2h[k] >= v ? v : m2h[k]
end

puts "#{closed} #{bclosed}"

def read_array(size)
  a = []
  for _ in 1..size
    a << read_next_line
  end
  group(a)
end

def read_next_line
  gets.split.map { |x| x.to_i }
end

def group(a)
  Hash[a.inject(Hash.new { |h, e| h[e] = [] }) { |h, e| h[e[1]] << e[0]; h }.map { |k, v|
    [k, [v.inject(Hash.new(0)) { |h, e| h[e] += 1; h }, v.size]]
  }]
end

n, m = read_next_line
markers = read_array(n)
caps = read_array(m)

closed = b_closed = 0
markers.each { |d, c|
  if caps.has_key? d
    closed += [c[1], caps[d][1]].min
    c[0].each { |k, v|
      if caps[d][0].has_key? k
        b_closed += [v, caps[d][0][k]].min
      end
    }
  end
}
puts "#{closed} #{b_closed}"

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

closed = 0
beautifully_closed = 0
current_size = -1
i = 0 # marker index
j = 0 # cap index
while i < markers.length && j < caps.length
	unclosed_markers = 0
	unused_caps = 0
	current_size = markers[i][1] # or = caps[j][1]
	while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && markers[i][0] == caps[j][0]
			closed += 1
			beautifully_closed += 1
			i += 1
			j += 1
		end
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && markers[i][0] < caps[j][0]
			unclosed_markers += 1
			i += 1
		end
		while i < markers.length && j < caps.length && markers[i][1] == current_size && caps[j][1] == current_size && caps[j][0] < markers[i][0]
			unused_caps += 1
			j += 1
		end
		if j >= caps.length || caps[j][1] != current_size
			while i < markers.length && markers[i][1] == current_size
				unclosed_markers += 1
				i += 1
			end
		end
		if i >= markers.length || markers[i][1] != current_size
			while j < caps.length && caps[j][1] == current_size
				unused_caps += 1
				j += 1
			end
		end
	end
	closed += unclosed_markers < unused_caps ? unclosed_markers : unused_caps
	while i < markers.length && j < caps.length && markers[i][1] < caps[j][1]
		i += 1
	end
	while i < markers.length && j < caps.length && caps[j][1] < markers[i][1]
		j += 1
	end
end

puts "#{closed} #{beautifully_closed}"

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
cups = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
cups = cups.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

closed = 0
beautifully_closed = 0

markers_map = {}
markers.each do |marker|
	markers_map[marker[1]] = {-1 => 0}unless markers_map.key?(marker[1])
	markers_map[marker[1]][marker[0]] = 0 unless markers_map[marker[1]].key?(marker[0])
	markers_map[marker[1]][marker[0]] += 1
	markers_map[marker[1]][-1] += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]].key?(cups[i][0]) && markers_map[cups[i][1]][cups[i][0]] > 0
			markers_map[cups[i][1]][cups[i][0]] -= 1
			markers_map[cups[i][1]][-1] -= 1
			beautifully_closed += 1
			closed += 1
			cups.delete_at(i)
			next
		end
	end
	i += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]][-1] > 0
			markers_map[cups[i][1]][-1] -= 1
			closed += 1
		end
	end
	i += 1
end

puts "#{closed} #{beautifully_closed}"

class Array
	def my_slice_when
		arr_groups = []
		arr = [self[0]]
		i = 1
		while i < self.length
			if yield(self[i - 1], self[i])
				arr_groups.push(arr)
				arr = [self[i]]
			else
				arr.push(self[i])
			end
			i += 1
		end
		arr_groups.push(arr)
		arr_groups
	end
end

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

markers_by_size = markers.my_slice_when { |a, b| a[1] != b[1] }
caps_by_size = caps.my_slice_when { |a, b| a[1] != b[1] }

closed = 0
beautifully_closed = 0
i = 0;
markers_by_size.each do |markers_size_group|
	size = markers_size_group[0][1]
	while i < caps_by_size.length && caps_by_size[i][0][1] < size
		i += 1
	end
	break if i >= caps_by_size.length
	next if caps_by_size[i][0][1] > size
	closed += markers_size_group.length < caps_by_size[i].length ? markers_size_group.length : caps_by_size[i].length

	markers_by_color = markers_size_group.my_slice_when { |a, b| a[0] != b[0] }
	caps_by_color = caps_by_size[i].my_slice_when { |a, b| a[0] != b[0] }
	j = 0;
	markers_by_color.each do |markers_color_group|
		color = markers_color_group[0][0]
		while j < caps_by_color.length && caps_by_color[j][0][0] < color
			j += 1
		end
		break if j >= caps_by_color.length
		next if caps_by_color[j][0][0] > color
		beautifully_closed += markers_color_group.length < caps_by_color[j].length ? markers_color_group.length : caps_by_color[j].length
	end
end

puts "#{closed} #{beautifully_closed}"

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
cups = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

closed = 0
beautifully_closed = 0

markers_map = {}
markers.each do |marker|
	markers_map[marker[1]] = {-1 => 0}unless markers_map.key?(marker[1])
	markers_map[marker[1]][marker[0]] = 0 unless markers_map[marker[1]].key?(marker[0])
	markers_map[marker[1]][marker[0]] += 1
	markers_map[marker[1]][-1] += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]].key?(cups[i][0]) && markers_map[cups[i][1]][cups[i][0]] > 0
			markers_map[cups[i][1]][cups[i][0]] -= 1
			markers_map[cups[i][1]][-1] -= 1
			beautifully_closed += 1
			closed += 1
			cups.delete_at(i)
			next
		end
	end
	i += 1
end

i = 0
while i < cups.length
	if markers_map.key?(cups[i][1])
		if markers_map[cups[i][1]][-1] > 0
			markers_map[cups[i][1]][-1] -= 1
			closed += 1
		end
	end
	i += 1
end

puts "#{closed} #{beautifully_closed}"

I = ->{gets.split.map(&:to_i)}
n, m = I[]
def r(n)
    h = {}
    n.times{
        x, y = I[]
        h[y] = h[y] || Hash.new(0)
        h[y][x] += 1
    }
    h
end
a, b, u, v = r(n), r(m), 0, 0
a.merge(b){|_, c, d|
    u += [c.size, d.size].min
    c.merge(d){|_, e, f|
        v += [e, f].min
    }
}
puts "#{u} #{v}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

beautiful = 0
closed = 0

markers.each_with_index do |m,_|
  if i = caps.index(m)
    caps.delete_at i
    markers.delete_at _
    beautiful += 1
    closed += 1
  end
end

markers.each_with_index do |m,_|
  if i = caps.index{|c| m[1] == c[1] }
    caps.delete_at i
    markers.delete_at _
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

beautiful = 0
closed = 0

markers.each do |(mc,md)|
  if i = caps.index{|(cc,cd)| mc == cc && md == cd }
    caps.delete_at i
    beautiful += 1
    closed += 1
  elsif i = caps.index{|(cc,cd)| md == cd }
    caps.delete_at i
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    beautiful += 1
    closed += 1
  end
end

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first[1]) && a.shift
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

n,m = STDIN.gets.chomp.split(/ /).map(&:to_i)
markers = n.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }
caps_ = m.times.map { STDIN.gets.chomp.split(/ /).map(&:to_i) }

caps = {}
caps_.each do |i|
  caps[i[1]] ||= {}
  caps[i[1]][i[0]] ||= []
  caps[i[1]][i[0]] << true
end

beautiful = 0
closed = 0
done = []

markers.each_with_index do |m,_|
  if (h = caps[m[1]]) && (a = h[m[0]]) && a.shift
    done << _
    beautiful += 1
    closed += 1
  end
end

done.each{|i| markers[i] = nil }

markers.each_with_index do |m,_|
  next unless m
  if (h = caps[m[1]]) && (a = h.first[1]) && a.shift
    closed += 1
  end
end

puts "#{closed} #{beautiful}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
m=arr[0...a[0]]
c=arr[a[0]...(a[0]+a[1])]

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
  arr1= c.map{|h| h[1]}.uniq
  closed += arr1.count{|val| val == pa[1]}
end
puts "#{closed} #{bclosed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
m=arr[0...a[0]].uniq
c=arr[a[0]...(a[0]+a[1])].uniq

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
end
m.map{|h| h[1]}.uniq.each do |v|
  closed += c.map{|h| h[1]}.count{|val| val == v}
end
puts "#{closed} #{bclosed}"

a = STDIN.gets.split(" ").map(&:to_i)
arr = (a[0]+a[1]).times.map{STDIN.gets.split(" ").map(&:to_i)}
p m=arr[0...a[0]].uniq
p c=arr[a[0]...(a[0]+a[1])].uniq

closed = 0
bclosed = 0
m.each do |pa|
  bclosed += c.count{|pair| pa == pair}
end
m.map{|h| h[1]}.uniq.each do |v|
  closed += c.map{|h| h[1]}.count{|val| val == v}
end
puts "#{closed} #{bclosed}"

class Array
	def my_slice_when
		arr_groups = []
		arr = [self[0]]
		i = 1
		while i < self.length
			if yield(self[i - 1], self[i])
				arr_groups.push(arr)
				arr = [self[i]]
			else
				arr.push(self[i])
			end
			i += 1
		end
		arr_groups.push(arr)
		arr_groups
	end
end

require 'scanf'
lines = STDIN.read.split("\n")
n, m = lines[0].scanf("%d%d")
markers = lines[1..n].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}
caps = lines[n+1..n+m].map { |line|
	split = line.split(' ')
	[Integer(split[0]), Integer(split[1])]
}

markers = markers.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }
caps = caps.sort { |a, b| a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : a[0] - b[0] }

markers_by_size = markers.my_slice_when { |a, b| a[1] != b[1] }
caps_by_size = caps.my_slice_when { |a, b| a[1] != b[1] }

closed = 0
beautifully_closed = 0
i = 0;
markers_by_size.each do |markers_size_group|
	size = markers_size_group[0][1]
	while i < caps_by_size.length && caps_by_size[i][0][1] < size
		i += 1
	end
	break if i >= caps_by_size.length || caps_by_size[i][0][1] > size
	closed += markers_size_group.length < caps_by_size[i].length ? markers_size_group.length : caps_by_size[i].length

	markers_by_color = markers_size_group.my_slice_when { |a, b| a[0] != b[0] }
	caps_by_color = caps_by_size[i].my_slice_when { |a, b| a[0] != b[0] }
	j = 0;
	markers_by_color.each do |markers_color_group|
		color = markers_color_group[0][0]
		while j < caps_by_color.length && caps_by_color[j][0][0] < color
			j += 1
		end
		break if j >= caps_by_color.length || caps_by_color[j][0][0] > color
		beautifully_closed += markers_color_group.length < caps_by_color[j].length ? markers_color_group.length : caps_by_color[j].length
	end
end

puts "#{closed} #{beautifully_closed}"


The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.

11 6
abacabadaba
a b
b c
a d
e g
f a
b b

NoteIn the second sample the name of the corporation consecutively changes as follows:

A = ('a'..'z').to_a.join
n, m = gets.split.map(&:to_i)
s = gets.chomp
ds = m.times.map{gets.split}
a = A.dup
ds.each{|x, y| a.tr!(x + y, y + x)}
puts s.tr(A, a)

# http://codeforces.com/contest/591/problem/B
# B. Rebranding

hash = {}.tap do |h|
  ('a'..'z').each { |ch| h[ch] = ch }
end
n, m = gets.chomp.split.map(&:to_i)
chars = gets.chomp.chars

m.times do
  a, b = gets.split

  tmp = hash[a]
  hash[a] = hash[b]
  hash[b] = tmp
end
invert = hash.invert
puts chars.map { |ch| invert[ch] }.join

n = gets.split(' ')[1].to_i
s = gets
hash = {}
"a".upto("z") { |s| hash[s] = s }
n.times do
    a = gets.split(' ')
    k1 = hash.key(a[0])
    k2 = hash.key(a[1])
    tmp = hash[k1]
    hash[k1] = hash[k2]
    hash[k2] = tmp
end

hash.each { |key, value|
    s.gsub!(key, value.upcase)
}

puts s.downcase

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
name = gets.chomp
design = Array.new(m)
for i in 0...m
    design[i] = gets.chomp.split
end

#puts design

replace = Array.new(26) {|i| i }
rev_replace = Array.new(26) {|i| i }

for i in 0...design.length
    x, y = design[i]
    if x != y
        x = x.ord - 97
        y = y.ord - 97
        a = rev_replace[x]
        b = rev_replace[y]
        replace[a] = y
        rev_replace[y] = a

        replace[b] = x
        rev_replace[x] = b
    end
end

for i in 0...n
    print (replace[name[i].ord - 97] + 97).chr
end

puts

n, m = gets.split.map(&:to_i)
s = gets.chomp
ds = m.times.map{gets.split}
a = ('a'..'z').to_a
ds.each do |x, y|
  26.times do |i|
    if a[i] == x
      a[i] = y
    elsif a[i] == y
      a[i] = x
    end
  end
end
n.times do |i|
  s[i] = a[s[i].ord - 'a'.ord]
end
puts s

n, m = gets.split.map(&:to_i)
str = gets.chomp
str1 = str.clone
result, uniq = [], []
while str1.size > 0 do
  uniq << str1[0]
  str1.delete!(str1[0])
end
uniq_arr = Array.new(uniq.length){ Array.new }
i = 0
str.each_char do |s|
  uniq.each_with_index do |u, index|
    if s == u
      uniq_arr[index] << i
      break
    end
  end
  i += 1
end
(1..m).each do |i|
  x, y = gets.split
  next if x == y
  i = 0
  uniq.each do |c|
    uniq[i] = y if c == x
    uniq[i] = x if c == y
    i += 1
  end
end
uniq.each_with_index do |u, index|
  uniq_arr[index].each do |i|
    result[i] = u
  end
end
puts result.join()

class Solver
	def main
		n, m = gets.split.map { |s| s.to_i }
		str = gets

		pos = Array.new(128) { |id, v| v = id }
		to = Array.new(128) { |id, v| v = id }
		m.times do
			a, b = gets.split.map { |c| c.ord }
			to[pos[a]], to[pos[b]] = to[pos[b]], to[pos[a]]
			pos[a], pos[b] = pos[b], pos[a]
		end

		n.times do |i|
			print to[str[i].ord].chr
		end
		print ?\n

	end
end

Solver.new.main

n = gets.split(' ')[1].to_i
s = gets
hash = {}
n.times do
    a = gets.split(' ')
    hash[a[0]] = a[1]
    hash[a[1]] = a[0]
end

hash.each { |key, value|
    s.gsub!(key, value.upcase)
}

puts s.downcase

n = gets.split(' ')[1].to_i
s = gets
hash = {}
"a".upto("z") { |s| hash[s] = s }
n.times do
    a = gets.split(' ')
    tmp = hash[a[0]]
    hash[a[0]] = hash[a[1]]
    hash[a[1]] = tmp
end

hash.each { |key, value|
    s.gsub!(key, value)
}

puts s

n = gets.split(' ')[1].to_i
s = gets
n.times do
    a = gets.split(' ')
    s.gsub!(a[0], a[1])
end

puts s

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
name = gets.chomp.split("")
design_request = []
for i in 0...m
    design_request[i] = []
    design_request[i] = gets.chomp.split
end
design = []
for i in 0...m
    if design_request[i][0] != design_request[i][1]
        design.push(design_request[i])
    end
end

l = design.length
x = design[0][0]
y = design[0][1]
replace = [design[0], [y, x]]

for i in 1...l
    a = 0
    b = 0
    for j in 0...replace.length
        if replace[j][1] == design[i][0]
            replace[j][1] = design[i][1]
            a = 1
            break
        end
        if replace[j][1] == design[i][1]
            replace[j][1] = design[i][0]
            b = 1
        end
    end
    if a == 0
        replace.push(design[i])
    end
    if b == 0
        replace.push([design[i][1], design[i][0]])
    end
end

for i in 0...n
    for j in 0...replace.length
        if name[i] == replace[j][0]
            name[i] = replace[j][1]
            break
        end
    end
end
print name.join
puts

l = gets.to_i
p = gets.to_i
q = gets.to_i

puts l * ( p * 1.0 / (p + q) )