Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that:   the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN",  or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of clubs in the league. Each of the next n lines contains two words — the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20.

It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them.

3
PLAYFOOTBALL MOSCOW
PLAYVOLLEYBALL SPB
GOGO TECHNOCUP

NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different.

#!/usr/bin/env ruby

class Array
  def my_chunk_while(&blk)
    self.reduce([]) do |s, x|
      if s.empty?
        s << [x]
        # elsif s[-1][0][0] == x[0]
      elsif blk[s[-1][0], x]
        s[-1] << x
        s
      else
        s << [x]
      end
    end
  end

end

class FootballLeague
  attr_accessor :n, :src, :result

  def init
    @src = @src.map {|x| x=x.split;[x[0][0..1],x[0][2],x[1][0]]}  # [[ab,c,d],...]
    tmp = []
    @src = @src.each_with_index { |obj, ind | tmp <<[obj,ind] }   # [[[ab,c,d],0],...]
    @src = tmp.sort {|a,b| a=a[0].join;b=b[0].join;a<=>b}         # order by ab,c,d
    tmp=[]
    @src = @src.my_chunk_while {|i,j| i[0][0] == j[0][0]}.to_a             # [[[[ab,c,d],i],[[ab,l,f],k],...], ..]
    @result="YES"
  end

  def getResult
    init
  ->{@src.map do |x|                                              # x: [[[ab,c,d],i],[[ab,l,f],k],...]
      if x.length == 1
      x[0][0] = x[0][0][0]+x[0][0][1]                             # x[0]: [[ab,c,d],i]
      elsif x.group_by {|a| a[0][1]}.length == x.length
          x.map {|s| s[0]=s[0][0]+s[0][1]}
      # elsif x.my_chunk_while {|a,b| a[0][2] == b[0][2]}.to_a.length == x.length
      elsif x.group_by {|a| a[0][2]}.length == x.length
        x.map {|s| s[0]=s[0][0]+s[0][2]}
      else
        @result = "NO"
        return
      end
  end}[]
    printResult
  end

  def printResult
    if @result == "NO"
      @src = []
      @result
    else
      tmp=[]
      @src.each {|x| x.each {|y| tmp<<y}}
      @src = tmp.sort {|a,b| a[1]<=>b[1] }
      @src = @src.map {|x| x[0]}
    end
    [@result,@src]
  end
end

if __FILE__ == $0
  fl = FootballLeague.new
  fl.n = $stdin.readline.to_i
  fl.src = $stdin.readlines
  fl.getResult
  puts fl.result
  puts fl.src.join("\n") if fl.result == "YES"
end

#!/usr/bin/env ruby

class Array
  def my_chunk_while(&blk)
    self.reduce([]) do |s, x|
      if s.empty?
        s << [x]
        # elsif s[-1][0][0] == x[0]
      elsif blk[s[-1][0], x]
        s[-1] << x
        s
      else
        s << [x]
      end
    end
  end
end

class FootballLeague
  attr_accessor :n, :src, :result

  def init
    @src = @src.map {|x| x=x.split;[x[0][0..1],x[0][2],x[1][0]]}  # [[ab,c,d],...]
    tmp = []
    @src = @src.each_with_index { |obj, ind | tmp <<[obj,ind] }   # [[[ab,c,d],0],...]
    @src = tmp.sort {|a,b| a=a[0].join;b=b[0].join;a<=>b}         # order by ab,c,d
    tmp=[]
    @src = @src.my_chunk_while {|i,j| i[0][0] == j[0][0]}.to_a             # [[[[ab,c,d],i],[[ab,l,f],k],...], ..]
    @result="YES"
  end

  def getResult
    init
  ->{@src.map do |x|                                              # x: [[[ab,c,d],i],[[ab,l,f],k],...]
      if x.length == 1
      x[0][0] = x[0][0][0]+x[0][0][1]                             # x[0]: [[ab,c,d],i]
      elsif x.my_chunk_while {|a,b| a[0][1] == b[0][1]}.to_a.length == x.length
          x.map {|s| s[0]=s[0][0]+s[0][1]}
      elsif x.my_chunk_while {|a,b| a[0][2] == b[0][2]}.to_a.length == x.length
        x.map {|s| s[0]=s[0][0]+s[0][2]}
      else
        @result = "NO"
        return
      end
  end}[]
    printResult
  end

  def printResult
    if @result == "NO"
      @src = []
      @result
    else
      tmp=[]
      @src.each {|x| x.each {|y| tmp<<y}}
      @src = tmp.sort {|a,b| a[1]<=>b[1] }
      @src = @src.map {|x| x[0]}
    end
    [@result,@src]
  end
end

if __FILE__ == $0
  fl = FootballLeague.new
  fl.n = $stdin.readline.to_i
  fl.src = $stdin.readlines
  fl.getResult
  puts fl.result
  puts fl.src.join("\n") if fl.result == "YES"
end


Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $$$x$$$ as nearly prime if it can be represented as $$$p \cdot q$$$, where $$$1 < p < q$$$ and $$$p$$$ and $$$q$$$ are prime numbers. For example, integers $$$6$$$ and $$$10$$$ are nearly primes (since $$$2 \cdot 3 = 6$$$ and $$$2 \cdot 5 = 10$$$), but integers $$$1$$$, $$$3$$$, $$$4$$$, $$$16$$$, $$$17$$$ or $$$44$$$ are not.Captain Flint guessed an integer $$$n$$$ and asked you: can you represent it as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains the single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the number Flint guessed.

For each test case print:    YES and $$$4$$$ different positive integers such that at least $$$3$$$ of them are nearly prime and their sum is equal to $$$n$$$ (if there are multiple answers print any of them);  NO if there is no way to represent $$$n$$$ as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them are nearly prime.  YES NO

NoteIn the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.In the third test case, $$$n=31=2 \cdot 7 + 2 \cdot 5 + 2 \cdot 3 + 1$$$: integers $$$14$$$, $$$10$$$, $$$6$$$ are nearly prime.In the fourth test case, $$$n=36=5 + 2 \cdot 3 + 2 \cdot 5 + 3 \cdot 5$$$: integers $$$6$$$, $$$10$$$, $$$15$$$ are nearly prime.In the fifth test case, $$$n=44=2 \cdot 3 + 7 + 2 \cdot 5 + 3 \cdot 7$$$: integers $$$6$$$, $$$10$$$, $$$21$$$ are nearly prime.In the sixth test case, $$$n=100=2 + 2 \cdot 5 + 3 \cdot 11 + 5 \cdot 11$$$: integers $$$10$$$, $$$33$$$, $$$55$$$ are nearly prime.In the seventh test case, $$$n=258=2 \cdot 5 + 3 \cdot 7 + 13 \cdot 17 + 2 \cdot 3$$$: integers $$$10$$$, $$$21$$$, $$$221$$$, $$$6$$$ are nearly prime.

t=gets.chomp.to_i
rep=15
while t!=0
 ar=[6,10,14]
 sum=30
 num=gets.chomp.to_i
 ar.each_with_index do |x,i|
 if (num-sum == x)
  ar[ar.length-1]=rep
  sum+=1
  break
 end

 end
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 puts
 else
     puts "NO"
end
t-=1
end

n = gets.chomp.to_i
n.times do |i|
    s = gets.chomp
    if s.to_i >= 31 && s != "36" && s != "40" && s != "44"
    puts "YES"
    print "6"
    print " "
    print "10"
    print " "
    print "14"
    print " "
    print s.to_i - 30
        print "\n"
    elsif s == "40" || s == "36" || s == "44"
        puts "YES"
        print "6"
        print " "
        print "10"
        print " "
        print "15"
        print " "
        print s.to_i - 31
            print "\n"
    else
        puts "NO"
    end
end

$, = " "
$\ = "\n"
gets.to_i.times do
    n = gets.to_i
    if n <= 30
        puts "NO"
    else
        puts "YES"
        if n == 36 || n == 40 || n == 44
            print 6, 10, 15, n - 31
        else
            print 6, 10, 14, n - 30
        end
    end
end

t= gets.chomp.to_i
ar=[6,10,14]
sum = 30
while t!=0
 num= gets.chomp.to_i
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 else
     puts "NO"
end
t-=1
end

t=gets.chomp.to_i
ar=[6,10,14]
rep=15
sum = 30
while t!=0
 num=gets.chomp.to_i
 ar.each_with_index do |x,i|
 if (num-sum == x)
   puts"in if"
  ar[ar.length-1]=rep
  sum+=1
  break
 end

 end
 p "sum = #{sum}"
 ar.each {|x| puts x}
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 puts
 else
     puts "NO"
end
t-=1
end

t= gets.chomp.to_i
ar=[6,10,14]
sum = 30
while t!=0
 num= gets.chomp.to_i
if(num-sum >= 1)
 puts "YES"
 print "#{num-sum} "
 ar.each { |x| print "#{x} "}
 else
     puts "NO"
end
t-=1
end

t=gets.chomp.to_i

rep=15
sum = 30
while t!=0
 ar=[6,10,14]
 num=gets.chomp.to_i
 ar.each_with_index do |x,i|
 if (num-sum == x)
  ar[ar.length-1]=rep
  sum+=1
  break
 end

 end
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 puts
 else
     puts "NO"
end
t-=1
end

t=gets.chomp.to_i
ar=[6,10,14]
rep=15
sum = 30
while t!=0
 num=gets.chomp.to_i
 ar.each_with_index do |x,i|
 if (num-sum == x)
  ar[ar.length-1]=rep
  sum+=1
  break
 end

 end
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 puts
 else
     puts "NO"
end
t-=1
end

t= gets.chomp.to_i
ar=[6,10,14]
sum = 30
while t!=0
 num= gets.chomp.to_i
if(num-sum >= 1)
 puts "YES"
 ar.each { |x| print "#{x} "}
 print "#{num-sum}"
 puts
 else
     puts "NO"
end
t-=1
end

n = gets.chomp.to_i
n.times do |i|
    s = gets.chomp.to_i
    if s >= 31
    puts "YES"
    print "6"
    print " "
    print "10"
    print " "
    print "14"
    print " "
    print s - 30
        print "\n"
    else
        puts "NO"
    end
end

n = gets.chomp.to_i
n.times do
    s = gets.chomp.to_i
    if n >= 31
    puts "YES"
    print "6"
    print " "
    print "10"
    print " "
    print "14"
    print s - 30
    else
        puts "NO"
    end
end

$, = ' '
gets.to_i.times do
    n = gets.to_i
    if n <= 30
        puts "NO"
    else
        puts "YES"
        if n == 36 || n == 40 || n == 44
            print 6, 10, 15, n - 31
        else
            print 6, 10, 14, n - 30
        end
    end
end

n = gets.to_i
ans = []
n.times do
  x = gets.to_i
  if x <= 30
    ans << [-1,-1,-1,-1]
  else
    ans << [6,10,14,x-30]
  end
end
ans.each do |x|
  if x[0] == -1
    puts "NO"
  else
    puts "YES"
    puts "#{x[0]} #{x[1]} #{x[2]} #{x[3]}"
  end
end


Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number ai (1 ≤ ai ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

Print the minimum total time to finish all tasks modulo 10 007.

NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.

n = gets.strip.to_i
tasks = Array.new(n, 0)
laziness = Array.new(n, 0)
n.times do |i|
    a = gets.strip.to_i
    tasks[i] = laziness[i] = a
end
tasks.sort!.reverse!
laziness.sort!
ans = 0
n.times do |i|
    ans += tasks[i] * laziness[i]
end
ans %= 10007
puts ans

n = gets.strip.to_i
arr = []
n.times do
  arr << gets.strip.to_i
end
arr.sort!
sum = 0
for i in 0..((n-1)/2) do
  if i != n-1-i
    sum += arr[i] * arr[n-1-i] * 2
  else
    sum += arr[i] * arr[i]
  end
end
puts (sum % 10007)

n = gets.strip.to_i
tasks = Array.new(n, 0)
laziness = Array.new(n, 0)
n.times do |i|
    a = gets.strip.to_i
    tasks[i] = laziness[i] = a
end
tasks.sort!.reverse!
laziness.sort!
ans = 0
n.times do |i|
    ans += tasks[i] * laziness[i]
end
puts ans

n = gets.strip.to_i
arr = []
n.times do
  arr << gets.strip.to_i
end
arr.sort!
sum = 0
for i in 0..((n-1)/2) do
  if i != n-1-i
    sum += arr[i] * arr[n-1-i] * 2
  else
    sum += arr[i] * arr[i]
  end
end
puts sum


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.

n = gets.chomp.to_i
row = Array.new(n, false)
col = Array.new(n, false)

all = n * n
ans = []
all.times do |day|
  r, c = gets.chomp.split(' ').map(&:to_i)
  next if row[r - 1] || col[c - 1]
  row[r - 1] = true
  col[c - 1] = true
  ans << day + 1
end

puts ans.join(' ')

n=gets.to_i
a = []
b = []

out= []
(n*n).times do |i|
	x,y = gets.split(" ").map(&:to_i)
	if (!a[x] && !b[y])
		out << i+1
		a[x] = true
		b[y] = true
	end
end

puts out.join(" ")

h,v, days = [], [], []
n = gets.chomp.to_i
(n**2).times do |t|
	hi, vi = gets.chomp.split(" ").map(&:to_i)
	if !h.include?(hi) and !v.include?(vi)
		h << hi
		v << vi
		days << (t+1)
	end
end
puts days.join " "

n = STDIN.gets.strip.to_i
hs = Array.new(n+1, false)
vs = Array.new(n+1, false)
days = []
(n*n).times do |d|
  h, v = STDIN.gets.strip.split(" ").map{|i| i.to_i}
  next if hs[h] || vs[v]
  hs[h] = vs[v] = true
  days << d + 1
end

puts days.sort.join(" ")

n = gets.to_i
a = Array.new(n){false}
b = Array.new(n){false}
(n*n).times{ |i|
  x, y = gets.split(" ").map(&:to_i)
  if !a[x] && !b[y]
    print (i+1).to_s + " "
    a[x] = true
    b[y] = true
  end
}

a=gets.chomp.to_i
h=[]
v=[]
temp=gets.chomp.split(" ")
h[0]=temp[0]
v[0]=temp[1]
printf "1 "
if a>1
2.upto(a*a) do |i|
temp=gets.chomp.split(" ")
if h.count("#{temp[0]}")==0 && v.count("#{temp[1]}")==0
h << temp[0]
v << temp[1]
printf "#{i} "
end
end
end

n = gets.chomp.to_i
arr = []
for i in (0..(n**2)-1)
	arr[i] = gets.chomp.split.map(&:to_i)
end

h = []
v = []
h[0] = arr[0][0]
v[0] = arr[0][1]

print 1
print " "
for i in (1..(n**2)-1)
	if h.include?(arr[i][0]) == false && v.include?(arr[i][1]) == false
		print i+1
		print " "
		h << arr[i][0]
		v << arr[i][1]
	end
end

def main
  n = gets.chomp.to_i
  i = n * n
  ints = []
  i.times do
    h, v = gets.chomp.split.map {|r| r.to_i}
    ints << [h, v]
  end

  hhash = {}
  vhash = {}

  days = []
  ints.each_with_index do |a, i|
    h, v = a
    if not hhash[h] and not vhash[v]
      hhash[h] = :done
      vhash[v] = :done
      days << i+1
    end
  end

  days.each do |d|
    print "#{d} "
  end

  puts ""

end

main

n = gets.to_i
x = []
y = []
ans = []
(n * n).times do |a|
  i, j = gets.split.map(&:to_i)
  next if x[i] || y[j]
  x[i] = true
  y[j] = true
  ans << a + 1
end
puts ans.join(' ')

n = gets.to_i
x = Array.new(n, false)
y = Array.new(n, false)
ans = []
(n * n).times do |a|
  i, j = gets.split.map(&:to_i)
  next if x[i] || y[j]
  x[i] = true
  y[j] = true
  ans << a + 1
end
puts ans.join(' ')

ans = [ ]

n = gets.strip.to_i
h_road = Array.new(n, false)
v_road = Array.new(n, false)

(n * n).times do |i|
  h, v = gets.strip.split(' ').map(&:to_i)
  h -= 1
  v -= 1

  if !h_road[h] and !v_road[v]
    ans.push(i + 1)
    h_road[h] = true
    v_road[v] = true
  end
end

puts ans.sort.join(' ')

#$stdin = File.open('in.txt')
#$stdout = File.open('out.txt', 'w')

n = gets.to_i

ur = []
uc = []

(1..(n*n)).each { |i|
  r, c = gets.split.map(&:to_i)
  if ur[r] == nil && uc[c] == nil
    ur[r] = 1
    uc[c] = 1
    p i
  end
}

a=gets.chomp.to_i
h=[]
v=[]
temp=gets.chomp.split(" ")
h[0]=temp[0]
v[0]=temp[0]
printf "1 "
if a>1
2.upto(a*a) do |i|
temp=gets.chomp.split(" ")
if h.count("#{temp[0]}")==0 && v.count("#{temp[1]}")==0
h << temp[0]
v << temp[1]
printf "#{i} "
end
end

end

a=gets.chomp.to_i
h=[]
v=[]
temp=gets.chomp.split(" ")
h[0]=temp[0]
v[0]=temp[1]
printf "1 "
if a>1
2.upto(a*a) do |i|
puts "#{i}"

temp=gets.chomp.split(" ")
if h.count("#{temp[0]}")==0 && v.count("#{temp[1]}")==0
h << temp[0]
v << temp[1]
printf "#{i} "
end
end

end

n = gets.chomp.to_i
arr = []
for i in (0..(n**2)-1)
	arr[i] = gets.chomp.split.map(&:to_i)
end

h = []
v = []
h[0] = arr[0][0]
v[0] = arr[0][1]

print 1
print " "
for i in (1..(n**2)-1)
	if h.include?(arr[i][0]) == false && v.include?(arr[i][1]) == false
		print i+1
		h << arr[i][0]
		v << arr[i][1]
	end
end


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

def nxt(t, s, d)
  tmp = [t - s, 0].max
  tmp = (tmp + d - 1) / d
  return s + tmp * d
end

n, t = gets.to_i, 0
for i in (1..n) do
  t = t + 1
  s, d = gets.split
  t = nxt(t, s.to_i, d.to_i)
end
print t

n = gets.to_i
ans = 0
n.times do |i|
    x, y = gets.split.map(&:to_i)
    tmp = ans - x
    if tmp < 0
        ans = x
    elsif tmp % y == 0
        ans = (tmp / y + 1) * y + x
    else
        ans = (tmp + y - 1) / y * y + x
    end
end
puts ans

def antimod(x, m)
  return (m - x % m) % m
end
n = gets.to_i
k = 0
n.times { |i|
  sd = gets.split().map{|a| a.to_i}
  if i == 0
    k = sd[0]
  else
    if sd[0] > k
      k = sd[0]
    else
      k = sd[0] + ((k-sd[0])/sd[1]+1)*sd[1]
    end
  end
}
puts k

n = gets.to_i
ans = 0
n.times do |i|
    x, y = gets.split.map(&:to_i)
    tmp = [ans - x, 0].max
    if i == 0
        ans = x
    elsif tmp % y == 0
        ans = (tmp / y + 1) * y + x
    else
        ans = (tmp + y - 1) / y * y + x
    end
end
puts ans


There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.

You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 3025$$$) — the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,\,b,\,c,\,d \le 9$$$; $$$d \leq a$$$; $$$b \leq c$$$).  One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.

For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.

NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario:   there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively;  $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively;  and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively.  Hence the total point score of the participant on the 100-th place is $$$12$$$.

gets.chomp.to_i.times do |_i|
  a, b, c, d = gets.split.map(&:to_i)
  p [a + b, c + d].max
end

gets.to_i.times do
  a, b, c, d = gets.split.map &:to_i
  puts [a + b, c + d].max
end


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

n = gets.to_i
l = []
r = []
somme = 0

for i in 1..n
  c = gets.split(' ')
  l[i] = c[0].to_i
  r[i] = c[1].to_i
  somme += ( l[i] - r[i] )
end

max = -1

pos = 0

for i in 1..n
  if max < ( somme - 2 * (l[i]-r[i]) ).abs and somme.abs < ( somme - 2 * (l[i]-r[i]) ).abs
    max = ( somme - 2 * (l[i]-r[i]) ).abs
    pos = i
  end
end

puts pos

def tuyet_doi abc
  abc > 0 ? abc : -abc
end

def beauty a_left, a_right
  a_left.inject(0){ |product,x| product + x } - a_right.inject(0){ |product,x| product + x }
end

def total arr_x
  arr_x.inject(0){ |product,x| product + x }
end

def more_beauty? a_left, a_right, n
  now_beauty = tuyet_doi(beauty(a_left, a_right))
  t_left = total(a_left)
  t_right =total(a_right)
  save = -1

  (0..n-1).each do |x|
    t_left1 = t_left + a_right[x] - a_left[x]
    t_right1 = t_right - a_right[x] + a_left[x]

    if tuyet_doi(t_left1 - t_right1) > now_beauty
      now_beauty = tuyet_doi(t_left1 - t_right1)
      save = x
    end
  end

  return save
  # if save == -1
  #   return -1
  # else
  #   return save
  # end
end

# input processor
n = gets.to_i
a_left = Array.new
a_right = Array.new
(1..n).each do |x|
  a = gets
  jump_list = a.split(" ")
  a_left << jump_list[0].to_i
  a_right << jump_list[1].to_i
end
beauty1 = more_beauty? a_left, a_right, n
beauty2 =  more_beauty? a_right, a_left, n
puts beauty1 > beauty2 ? beauty1 + 1 : beauty2 + 1

n = gets.chomp.to_i
lefts, rights = [], []
n.times do
  left, right = gets.chomp.split.map(&:to_i)
  lefts << left
  rights << right
end
sum_of_lefts, sum_of_rights = lefts.inject(:+), rights.inject(:+)
diff = (sum_of_lefts - sum_of_rights).abs

arr = []
lefts.zip(rights).each.with_index.map { |e, idx| [*e, idx] }.each do |left, right, idx|
  c = sum_of_lefts - left + right
  d = sum_of_rights - right + left
  arr << (c - d).abs
end

ans = arr.max
if diff >= ans
  puts 0
else
  puts arr.index(ans) + 1
end

n=gets.chomp.to_i
i=0
ls=0
rs=0
mini=0
maxi=0
min=500
max=-500
n.times do
    a=gets.chomp.split(" ")
    l=a[0].to_i
    r=a[1].to_i
    ls=ls+l
    rs=rs+r
    d=l-r
    if(d>max)
        max=d
        maxi=i+1
    end
    if(d<min)
        min=d
        mini=i+1
    end
    i+=1
end
b=ls-rs
b1=b-2*min
b2=-b+2*max
b=b.abs
b1=b1.abs
b2=b2.abs
c=[b,b1,b2].max
if (c==b)
    puts 0
elsif(c==b2)
    puts maxi
else
    puts mini
end

n = gets.to_i
ary = []
n.times do
  ary <<  (gets.split.map(&:to_i))
end
ans = 0
tmp = 0
lsum = ary.map{|x|x[0]}.inject(:+)
rsum = ary.map{|x|x[1]}.inject(:+)
beauty = (lsum - rsum).abs
# puts [lsum, rsum, beauty].inspect
ary.each_with_index do |x, i|
  tlsum = lsum - x[0] + x[1]
  trsum = rsum - x[1] + x[0]
  tbeauty = (tlsum - trsum).abs
  if tbeauty > beauty
    beauty = tbeauty
    ans = i + 1
  end
end
puts ans
# if lsum > rsum
#   ary.each_with_index do |x, i|
#     if x[1] > x[0] && (x[1]-x[0]) > tmp
#       tmp = (x[1]-x[0])
#       ans = i+1
#     end
#   end
# elsif lsum == rsum
#   ary.each_with_index do |x, i|
#     if x[0] != x[1] && (x[0]-x[1]).abs > tmp
#       tmp = (x[0]-x[1]).abs
#       ans = i+1
#     end
#   end
# else
#   ary.each_with_index do |x, i|
#     if x[0] > x[1] && (x[0]-x[1]) > tmp
#       tmp = (x[0]-x[1])
#       ans = i+1
#     end
#   end
# end

n=gets.to_i
s1=0
max1=[-(10**10),0]
min1=[10**10,0]

n.times{|i|
	a,b=gets.split.map{|e| e.to_i}
	d=2*b-2*a
	s1+=a-b
	if max1[0]<d then
		max1[0]=d
		max1[1]=i+1
	end
	if min1[0]>d then
		min1[0]=d
		min1[1]=i+1
	end
}

s2=(s1+min1[0]).abs
s3=(s1+max1[0]).abs
s1=s1.abs

if s1>=([s2,s3].max) then
	puts 0
elsif s2>=([s1,s3].max) then
	puts min1[1]
elsif s3>=([s1,s2].max) then
	puts max1[1]
else
	puts 0
end

n = gets.chomp.to_i
ls = []
rs = []
lt = 0
rt = 0
ans = 0
n.times do
  l, r = gets.chomp.split.map(&:to_i)
  ls << l
  rs << r
  lt += l
  rt += r
end

cur = (lt - rt).abs
for i in 0...n
  tmp = ((lt - ls[i] + rs[i]) - (rt - rs[i] + ls[i])).abs
  if cur < tmp
    ans = i + 1
    cur = tmp
  end
end
puts ans

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
ac = a.map{|x, y| x - y}
if ac.all?{|x| x < 0} || ac.all?{|x| x > 0}
  p 0
else
  cur = ac.inject(:+)
  mx, ind = 0, 0
  n.times do |i|
    c = (cur - 2 * ac[i]).abs
    if c > mx
      ind = i
      mx = c
    end
  end
  p ind + 1
end

l=[]
r=[]
n=gets.to_i
left=0
right=0
for i in 1..n
	a,b=gets.split(" ").map(&:to_i)
	left+=a
	right+=b
	l<<a
	r<<b
end
beauty=(left-right).abs
ans=0
for i in 0..n-1
	tmp=(left-right-2*l[i]+2*r[i]).abs
	if tmp>beauty
		beauty=tmp
		ans=i+1
	end
end
puts ans

n = gets.to_i
maxldiff = 0
maxlpos = 0
maxrdiff = 10**9
maxrpos = 0
suml = 0
sumr = 0
1.upto(n) do |i|
  l, r = gets.strip.split(' ').map(&:to_i)

  suml += l
  sumr += r
  diff = l - r

  if diff > maxldiff
    maxlpos = i
    maxldiff = diff
  end

  if maxrdiff > diff
    maxrpos = i
    maxrdiff = diff
  end
end

maxrdiff = -maxrdiff
if suml == sumr
  if maxldiff >= maxrdiff
    printf("%d\n", maxlpos)
  else
    printf("%d\n", maxrpos)
  end
else
  s1 = suml + maxrdiff
  s2 = sumr - maxrdiff

  s3 = suml - maxldiff
  s4 = sumr + maxldiff

  if (s1 - s2).abs > (s3 - s4).abs
    printf("%d\n", maxrpos)
  else
    printf("%d\n", maxlpos)
  end
end

n = gets.to_i
lr = (1..n).map{gets.split.map(&:to_i)}
diff = lr.map!{|x| x[0]-x[1]}
no_change = diff.reduce(&:+)
ans = [no_change.abs] + diff.map{|x| (no_change-2*x).abs}
puts ans.index(ans.max)

def tuyet_doi abc
  abc > 0 ? abc : -abc
end

def beauty a_left, a_right
  a_left.inject(0){ |product,x| product + x } - a_right.inject(0){ |product,x| product + x }
end

def total arr_x
  arr_x.inject(0){ |product,x| product + x }
end

def more_beauty? a_left, a_right, n
  now_beauty = tuyet_doi(beauty(a_left, a_right))
  t_left = total(a_left)
  t_right =total(a_right)
  save = -1

  (0..n-1).each do |x|
    t_left1 = t_left + a_right[x] - a_left[x]
    t_right1 = t_right - a_right[x] + a_left[x]
    tuyet_doi(t_left1 - t_right1) > now_beauty
    now_beauty = tuyet_doi(t_left1 - t_right1)
    save = x
  end
  if save == -1
    return 0
  else
    return save
  end
end

# input processor
n = gets.to_i
a_left = Array.new
a_right = Array.new
(1..n).each do |x|
  a = gets
  jump_list = a.split(" ")
  a_left << jump_list[0].to_i
  a_right << jump_list[1].to_i
end
beauty1 = more_beauty? a_left, a_right, n
beauty2 =  more_beauty? a_right, a_left, n
beauty1 > beauty2 ? beauty1 : beauty2

n=gets.to_i
s1=0
max1=[-(10**10),0]
min1=[10**10,0]

n.times{|i|
	a,b=gets.split.map{|e| e.to_i}
	d=2*b-2*a
	s1+=a-b
	if max1[0]<d then
		max1[0]=d
		max1[1]=i+1
	end
	if min1[0]>d then
		min1[0]=d
		min1[1]=i+1
	end
}

s2=(s1+min1[0]).abs
s3=(s1+max1[0]).abs
s1=s1.abs
if s1>[s2,s3].max then
	puts 0
elsif s2>[s1,s3].max then
	puts min1[1]
else
	puts max1[1]
end

n=gets.to_i
s1=0
max1=[-(10**10),0]
min1=[10**10,0]

n.times{|i|
	a,b=gets.split.map{|e| e.to_i}
	d=2*b-2*a
	s1+=a-b
	if max1[0]<d then
		max1[0]=d
		max1[1]=i+1
	end
	if min1[0]>d then
		min1[0]=d
		min1[1]=i+1
	end
}

s2=(s1+min1[0]).abs
s3=(s1+max1[0]).abs
s1=s1.abs

if s1>([s2,s3].max) then
	puts 0
elsif s2>([s1,s3].max) then
	puts min1[1]
elsif s3>([s1,s2].max) then
	puts max1[1]
else
	puts 0
end

n=gets.to_i
s1=0
max1=[-(10**10),0]
min1=[10**10,0]

n.times{|i|
	a,b=gets.split.map{|e| e.to_i}
	d=2*b-2*a
	s1+=a-b
	if max1[0]<d then
		max1[0]=d
		max1[1]=i+1
	end
	if min1[0]>d then
		min1[0]=d
		min1[1]=i+1
	end
}

if s1<0 then
	if min1[0]<0
		puts min1[1]
	else
		puts 0
	end
elsif s1>0 then
	if max1[0]>0
		puts max1[1]
	else
		puts 0
	end
else
	a=min1[0].abs
	b=max1[0].abs
	if a>b then
		puts min1[1]
	elsif a<b then
		puts max1[1]
	else
		puts min1[1]
	end
end

n = gets.to_i
a = n.times.map{gets.split.map(&:to_i)}
lc, rc = 0, 0
d = []
n.times do |i|
  l, r = a[i]
  if l > r
    lc += l - r
    d[i] = [l - r, 'l', i]
  elsif r > l
    rc += r - l
    d[i] = [r - l, 'r', i]
  else
    d[i] = [0, 'e', i]
  end
end
if lc == 0 || rc == 0
  puts 0
else
  lmx, rmx = nil, nil
  d.each do |x, y, z|
    if y == 'l' && (lmx.nil? || x > lmx[0])
      lmx = [x, y, z]
    elsif y == 'r' && (rmx.nil? || x > rmx[0])
      rmx = [x, y, z]
    end
  end
  if lc < rc || lmx[0] > rc
    puts lmx[2] + 1
  elsif lc > rc || rmx[0] > lc
    puts rmx[2] + 1
  else
    puts d.sort.last[2] + 1
  end
end

n = gets.to_i
lr = (1..n).map{gets.split.map(&:to_i)}
diff = lr.map!{|x| x[0]-x[1]}
no_change = diff.reduce(&:+)
ans = [no_change.abs, diff.map{|x| (no_change-2*x).abs}.min].min
puts ans.inspect


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

def slcm(s, lcmi)
    return s * (lcmi.to_i / s.length)
end

t = gets.chomp.to_i

while t > 0
    s = gets.chomp
    v = gets.chomp
    lcmi = s.length.lcm(v.length)
    lcmv = slcm v , lcmi
    lcms = slcm s , lcmi
    if lcms == lcmv
        puts v * (s.length.lcm(v.length)  / v.length)
    else
        puts "-1"
    end
    t-=1
end

t = gets.chomp.to_i
while t > 0
    s = gets.chomp
    v = gets.chomp
    lcmv = v * (s.length.lcm(v.length) / v.length)
    lcms = s * (s.length.lcm(v.length) / s.length)
    if lcms == lcmv
        puts v * (s.length.lcm(v.length) / v.length)
    else
        puts "-1"
    end
    t-=1
end

def read
    gets.chomp
end
gets.to_i.times do
    s, t = read, read
    n, m = s.size, t.size
    l = (n * m) / n.gcd(m)
    puts s * (l / n) == t * (l / m) ? s * (l / n) : -1
end

gets.to_i.times do
  s, t = gets.chomp, gets.chomp
  n, m = s.size, t.size
  sz = n * m / n.gcd(m)
  puts s * (sz / n) == t * (sz / m) ? s * (sz / n) : -1
end

a = gets.chomp.to_i

a.times do
    s1 = gets.chomp
    s2 = gets.chomp

    aux = ""
    s1.size.times do
        aux += s2
    end
    aux2 = ""
    s2.size.times do
        aux2 += s1
    end
    if aux != aux2
        puts -1
        next
    end

    lc = s1.size.lcm(s2.size)
    ss = [s1.size, s2.size].min

    num = lc/ss

    if ss == s2.size
        s1 = s2
    end
    aux = ""
    num.times do
        aux += s1
    end
    puts aux
end

gets.to_i.times do
  s=gets.chomp
  t=gets.chomp
  sz=s.size
  tz=t.size
  if s*tz==t*sz
    z=sz.lcm(tz)
    puts s*(z/sz)
  else
    puts "-1"
  end
end


You are given an integer $$$k$$$ and a string $$$s$$$ that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).Each asterisk should be replaced with several (from $$$0$$$ to $$$k$$$ inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.The result of the replacement is called a BA-string.Two strings $$$a$$$ and $$$b$$$ are different if they either have different lengths or there exists such a position $$$i$$$ that $$$a_i \neq b_i$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. Now consider all different BA-strings and find the $$$x$$$-th lexicographically smallest of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$k$$$ and $$$x$$$ ($$$1 \le n \le 2000$$$; $$$0 \le k \le 2000$$$; $$$1 \le x \le 10^{18}$$$). $$$n$$$ is the length of string $$$s$$$. The second line of each testcase is a string $$$s$$$. It consists of $$$n$$$ characters, each of them is either 'a' (a lowercase Latin letter) or '*' (an asterisk). The sum of $$$n$$$ over all testcases doesn't exceed $$$2000$$$. For each testcase $$$x$$$ doesn't exceed the total number of different BA-strings. String $$$s$$$ contains at least one character 'a'.

For each testcase, print a single string, consisting only of characters 'b' and 'a' (lowercase Latin letters) — the $$$x$$$-th lexicographically smallest BA-string.

NoteIn the first testcase of the example, BA-strings ordered lexicographically are:   a  ab  abb  abbb  abbbb In the second testcase of the example, BA-strings ordered lexicographically are:   aa  aba  abba Note that string "aba" is only counted once, even though there are two ways to replace asterisks with characters 'b' to get it.

gets.to_i.times do
  r=gets.strip.split(' ').map(&:to_i)
  x=r[2]-1
  s=gets.strip.gsub("a","ba").gsub("*b","*ab").split('a').map{|i|(i=='b'? 0:i.size*r[1]+1)}.reverse.map{|i|v='a';x/=((i!=0?(v='b'*(x%i)):false)?i :1);v}.reverse*''
  puts s
end

gets.to_i.times do
  r = gets.strip.split(' ').map(&:to_i)
  x = r[2] - 1
  s = gets.strip.gsub("a", "ba").gsub("*b", "*ab").split('a').map do |i|
    (i == 'b' ? 0 : i.size * r[1] + 1)
  end.reverse.map do |i|
    if i != 0
      ret = 'b' * (x % i)
      x /= i
      ret
    else
      ret = "a"
    end
  end.reverse * ''
  puts s
end

gets.to_i.times do
  r = gets.strip.split(' ').map(&:to_i)
  k = r[1]
  x = r[2] - 1
  s = gets.strip.gsub("a", "ba").gsub("*b", "*ab")
  s = s.split('a')
  s = s.map do |i|
    v = 0
    if (i != 'b')
      v = i.size
    end
    (i == 'b' ? 0 : v * k + 1)
  end.reverse.map do |i|
    ret = ""
    ret = "a" if i == 0
    if i != 0
      ret = ret + 'b' * (x % i)
      x /= i
    end
    ret
  end.reverse * ''
  puts s

end

gets.to_i.times do
  a,k,x=gets.strip.split(' ').map(&:to_i);x-=1
  puts gets.strip.split('').chunk{|x|x=='a'}.map{|a,b|a ?[0]*b.size: b.size*k}.flatten.reverse.map{|i|v=(i!=0?'b'*(x%(i+1)) :'a');x/=i+1;v}.reverse*''
end

gets.to_i.times do
  a,k,x=gets.strip.split(' ').map(&:to_i);x-=1
  puts gets.strip.split('').chunk{|x|x=='a'}.map{|a,b|a ?0: b.size*k}.reverse.map{|i|v=(i!=0?'b'*(x%(i+1)) :'a');x/=i+1;v}.reverse*''
end

gets.to_i.times do
  r = gets.strip.split(' ').map(&:to_i)
  n = r[0]
  k = r[1]
  x = r[2] - 1
  s = gets.strip.gsub("a", "ba").gsub("*b", "*ab")
  s = s.split('a')
  s = s.map do |i|
    v = 0
    if (i != 'b')
      v = i.size
    end
    v * k + 1
  end.reverse.map do |i|
    ret = ""
    ret = "a" if i == 1
    (x % i).times{ret += 'b'}
    x /= i
    ret
  end.reverse * ''
  puts s

end

gets.to_i.times do
  r = gets.strip.split(' ').map(&:to_i)
  n = r[0]
  k = r[1]
  x = r[2]
  s = gets.strip.gsub("a", "ba").gsub("*b", "*ab")
  s = s.split('a')
  s = s.map do |i|
    v = 0
    if (i != 'b')
      v = i.size
    end
    v * k + 1
  end
  v = 1
  x -= 1
  i = s.size() - 1
  flag = true
  vec = []
  s.each do |ele|
    vec.push("-")
  end
  while flag do
    if s[i] == 1
      i -= 1
      flag = i > -1 && v < x
    else
      vec[i] = [v, v * s[i]]
      v *= s[i]
      i = i - 1
      flag = i > -1 && v < x
    end
  end
  result = ""
  (0..(s.size() - 1)).each do |i|
    if vec[i] == "-"
      if s[i] == 1
        result += "a"
      end
    else
      if x > vec[i][0]
        ctr = x / vec[i][0]
        ctr = [ctr, s[i]].min
        x -= ctr * vec[i][0]
        result += "b" * ctr
      end
    end
  end
  puts result
end


Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: $$$s$$$ of length $$$n$$$ and $$$t$$$ of length $$$m$$$.A sequence $$$p_1, p_2, \ldots, p_m$$$, where $$$1 \leq p_1 < p_2 < \ldots < p_m \leq n$$$, is called beautiful, if $$$s_{p_i} = t_i$$$ for all $$$i$$$ from $$$1$$$ to $$$m$$$. The width of a sequence is defined as $$$\max\limits_{1 \le i < m} \left(p_{i + 1} - p_i\right)$$$.Please help your classmate to identify the beautiful sequence with the maximum width. Your classmate promised you that for the given strings $$$s$$$ and $$$t$$$ there is at least one beautiful sequence.

The first input line contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq m \leq n \leq 2 \cdot 10^5$$$) — the lengths of the strings $$$s$$$ and $$$t$$$. The following line contains a single string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the Latin alphabet. The last line contains a single string $$$t$$$ of length $$$m$$$, consisting of lowercase letters of the Latin alphabet. It is guaranteed that there is at least one beautiful sequence for the given strings.

Output one integer — the maximum width of a beautiful sequence.

NoteIn the first example there are two beautiful sequences of width $$$3$$$: they are $$$\{1, 2, 5\}$$$ and $$$\{1, 4, 5\}$$$.In the second example the beautiful sequence with the maximum width is $$$\{1, 5\}$$$.In the third example there is exactly one beautiful sequence — it is $$$\{1, 2, 3, 4, 5\}$$$.In the fourth example there is exactly one beautiful sequence — it is $$$\{1, 2\}$$$.

n,m = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp.chars
t = gets.chomp.chars
i = 0
arr = Array.new(m,-1)
m.times do |j|
  while s[i] != t[j]
    i += 1
  end
  arr[j] = i
  i += 1
end
max = 0
(m-1).times do |i|
  max = [max,arr[i+1]-arr[i]].max
end
i = n-1
(m-1).downto(1) do |j|
  while s[i] != t[j]
    i -= 1
  end
  arr[j] = i
  i -= 1
  max = [max, arr[j] - arr[j-1]].max
end
puts max

n,m=gets.split.map(&:to_i)
s=gets.chomp.chars
t=gets.chomp.chars
l=[]
i=0
j=0
while j<m
  if s[i]==t[j]
    l << i
    j+=1
  end
  i+=1
end
r=[]
i=n-1
j=m-1
while j>=0
  if s[i]==t[j]
    r << i
    j-=1
  end
  i-=1
end
r.reverse!
a=0
(m-1).times do |i|
  a=r[i+1]-l[i] if r[i+1]-l[i]>a
end
puts a

n,m = gets.chomp.split(" ").map(&:to_i)
s = gets.chomp.chars
t = gets.chomp.chars
i = 0
arr = Array.new(m,-1)
m.times do |j|
  while s[i] != t[j]
    i += 1
  end
  arr[j] = i
  i += 1
end
max = 0
(m-1).times do |i|
  max = [max,arr[i+1]-arr[i]].max
end
i = n-1
(m-1).downto(1) do |j|
  while s[i] != t[j]
    i -= 1
  end
  break if arr[j] == i
  arr[j] = i
  i -= 1
  max = [max, arr[j] - arr[j-1]].max
end
puts max


A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouquet should be odd. Each of the initial bouquets can be a part of at most one large bouquet. If an initial bouquet becomes a part of a large bouquet, all its flowers are included in the large bouquet.Determine the maximum possible number of large bouquets Vasya can make.

The first line contains a single positive integer n (1 ≤ n ≤ 105) — the number of initial bouquets. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the number of flowers in each of the initial bouquets.

Print the maximum number of large bouquets Vasya can make.

NoteIn the first example Vasya can make 2 large bouquets. For example, the first bouquet can contain the first and the fifth initial bouquets (the total number of flowers is then equal to 9), and the second bouquet can consist of the second and the third initial bouquets (the total number of flowers is then equal to 7). The fourth initial bouquet is unused in this scheme. In the second example it is not possible to form a single bouquet with odd number of flowers.In the third example Vasya can make one large bouquet. For example, he can make it using all three initial bouquets. The size of the large bouquet is then equal to 11 + 4 + 10 = 25.

b = gets.split.map{|_|_.to_i}
a = gets.split.map{|_|_.to_i}

even = 0
odd = 0
ans = 0

for x in a
	if x % 2 == 0
		even = even + 1
	else
		odd = odd + 1
	end
end

ans = ans + [odd, even].min
odd = odd - [odd, even].min
ans = ans + odd / 3

print(ans)

n = gets.to_i
ints = Array.new(n)
ints = gets.split.map{|x| x.to_i }
e=0
o=0
for x in ints
  if x%2 == 0
    e+=1
  else
    o+=1
  end
end

add = 0

if o>e
  add = (o-e) / 3
end
puts ([o,e].min + add)

n = 0
n = gets

a = gets.chomp.split().map { |e| e.to_i  }

even = 0
odd = 0

def min(a,b)
  if a < b
    a
  else
    b
  end
end

for i in 0...a.length
   if a[i] % 2 == 0
     even += 1
   else
     odd += 1
   end
end

ans = min(even,odd)
even -= ans
odd -= ans

ans += odd / 3

puts "#{ans}"

n = gets.to_i
a = Array.new(n)
a = gets.split(" ").collect{|x| x.to_i}
numo=0
numa=0
for i in 0...n
  if (a[i]%2==0)
      numo+=1
  end
end
numa=n-numo
if (numo>numa)
    ans=numa
else
    ans=numo
end
numa-=ans
if (numa>0)
    ans+=numa/3
end
print ans

n = gets.chomp()
nums = gets.scan(/\d+/).map(&:to_i)
odds = []
evens = []
cnt = 0
nums.each do |x|
  if x % 2 == 0
    evens << x
  else
    odds << x
  end
end
cnt += [odds.length, evens.length].min
el = odds.length - cnt
cnt += (el / 3) if el >= 3
# odds.each_with_index do |x, index|
#   unless evens[index].nil?
#     cnt += 1
#   else
#     break
#   end
# end
puts cnt

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

odd = 0
even = 0
for x in a
	if x%2==1
		odd+=1
	else
		even+=1
	end
end

if odd<=even
	puts odd
else
	puts even + (odd-even)/3
end

gets
b=0
c=0
gets.split.map{|e|
	e=e.to_i
	e%2 == 1? b+=1 : c+=1}

if b <= c
    puts b
else
    res = c
    b -= c
    res += b / 3
    puts res
end

r=->{gets.split.map &:to_i}
n=r[]
a=r[]
odd = 0
even = 0
for i in a
    if i % 2 == 0
        even = even + 1
    else
        odd = odd + 1
    end
end
ans = 0
if odd > even
    ans = even + (odd - even) / 3
elsif odd < even
    ans = odd
else
    ans = even
end
puts ans

n=gets.chomp.to_i
s=gets.chomp.split(' ')
res=0
odd=0
even=0
for x in s do
	odd=odd+(x.to_i % 2)
end
even=n-odd
if (even>=odd) then
	res=odd
else
	res=even+((odd-even)/3)
end
puts(res)

r=->{gets.split.map &:to_i}
n=r[]
a=r[]
odd = a.count{|_|_%2 == 1}
even = n[0] - odd
tk = 0
if odd > even then
    tk = even
else
    tk = odd
end
ans = tk
odd -= tk
even -= tk
p ans + (odd / 3)

r=->{gets.split.map &:to_i}
n=r[]
a=r[]
b=a.count{|_|_%2==1}
m=n.first
if b >= m-b
   p m-b+(b-m+b)/3
else
   p b
end

n = gets.to_i
a = gets.split.map &:to_i
odd = a.count{|_|_%2 == 1}
even = n - odd
ans = [odd,even].min
odd -= ans
ans += (odd / 3).floor

print ans

# require 'set'

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

even = a.select {|item|item % 2 == 0}
n_e = even.length
n_o = n - n_e
if n_e >= n_o then
	print n_o
else
	x = (n_o - n_e) / 3
	print n_e + x
end
# print even.length

# if (a.take(l - 1) == b.take(l - 1) && a.drop(r) == b.drop(r) && a1 == b1) then
# 	puts "TRUTH"
# else
# 	puts "LIE"
# end

n = gets.to_i
s = (gets.split)
s1=0
s2=0
for i in s
    a=i.to_i
    if a%2==0
        s2+=1
    else
        s1+=1
    end
end
if s1<=s2
    print s1
else
    print s2+(s1-s2)/3
end

N = gets.to_i
Arr = gets.chomp.split(' ').map(&:to_i)
even = 0
odd = 0
for i in Arr
    if (i%2==0)
        even = even + 1
    else
        odd = odd + 1
    end
end

ans = 0
if(even>odd)
    ans = odd
else
    ans = even
end

odd = odd - ans;

ans = ans + (odd/3)

p ans

n = gets.to_i
a = gets.split.map &:to_i
nodd = (a.keep_if &:odd?).size
neven = n - nodd
ans = [nodd, neven].min
nodd -= ans
ans += (nodd / 3).floor
p ans

r = ->{gets.split.map &:to_i}
n = r[]
a = r[]
cnt = 0
for x in a
  if x % 2 == 1
    cnt += 1
  end
end
if cnt < n[0] - cnt
  ans = cnt
else
  odd = cnt
  even = n[0] - cnt
  ans = even + ((odd - even) / 3)
end
p ans

n = gets.chomp
a = gets.chomp.split(' ')

odd = 0
even = 0

for u in a
    if u.to_i % 2 == 1
        odd += 1
    else
        even += 1
    end
end

if odd == 0
    puts 0
elsif even == 0
    puts odd / 3
else
    if odd > even
        puts even + (odd - even) / 3
    else
        puts odd
    end
end

a = gets.split

zoj = 0
fard = 0

n = a[0].to_i
b = gets.split

for i in (0..n - 1) do
	x = b[i].to_i
	if (x % 2 == 0)
	    zoj = zoj + 1
	else
	    fard = fard + 1
	end
end
mn = zoj
if (fard < zoj)
    mn = fard
end
fard = fard - mn
ezaf = fard / 3
mn = mn + ezaf
puts "#{mn}"

n = gets.to_i
ints = Array.new(n)
ints = gets.split.map{|x| x.to_i }
e=0
o=0
for x in ints
  if x%2 == 0
    e+=1
  else
    o+=1
  end
end

add = 0

if o>e
  add = o-e / 3
end
puts ([o,e].min + add)

n = gets.to_i
ints = Array.new(n)
ints = gets.split.map{|x| x.to_i }
e=0
o=0
for x in ints
  if x%2 == 0
    e+=1
  else
    o+=1
  end
end

puts ([o,e].min)

n = gets.chomp()
nums = gets.scan(/\d+/).map(&:to_i)
odds = []
evens = []
cnt = 0
nums.each do |x|
  if x % 2 == 0
    evens << x
  else
    odds << x
  end
end
odds.each_with_index do |x, index|
  unless evens[index].nil?
    cnt += 1
  else
    break
  end
end
puts cnt

n = gets.chomp()
nums = gets.scan(/\d+/).map(&:to_i)
odds = []
evens = []
cnt = 0
nums.each do |x|
  if x % 2 == 0
    evens << x
  else
    odds << x
  end
end
cnt = [odds.length, evens.length].min
# odds.each_with_index do |x, index|
#   unless evens[index].nil?
#     cnt += 1
#   else
#     break
#   end
# end
puts cnt

gets
b=0
c=0
gets.split.map{|e|
	e=e.to_i
	e%2 == 1? b+=1 : c+=1}
p b

n=gets.chomp.to_i
s=gets.chomp.split(' ')
res=0
odd=0
even=0
for x in s do
	odd=odd+(x.to_i % 2)
end
even=n-odd
if (even>=odd) then
	res=odd
else
	res=even+(odd-even)/2
end
puts(res)

n=gets.chomp.to_i
s=gets.chomp.split(' ')
res=0
for x in s do
	res=res+(x.to_i % 2)
end
puts(res)

# require 'set'

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

even = a.select {|item|item % 2 == 0}
n_e = even.length
n_o = n - n_e
print [n_o, n_e].min
# print even.length

# if (a.take(l - 1) == b.take(l - 1) && a.drop(r) == b.drop(r) && a1 == b1) then
# 	puts "TRUTH"
# else
# 	puts "LIE"
# end

n = gets.to_i
s = (gets.split)
s1=0
s2=0
for i in s
    a=i.to_i
    if a%2==0
        s2+=1
    else
        s1+=1
    end
end
if s1<=s2
    print s1
else
    print s2+s1/3
end

N = gets.to_i
Arr = gets.chomp.split(' ').map(&:to_i)
even = 0
odd = 0
for i in Arr
    if (i%2==0)
        even = even + 1
    else
        odd = odd + 1
    end
end

if(N==1)
    p 0
elsif(odd==0)
    p 0
else
    if(odd%2 == 0)
        p 2
    else
        p 1
    end
end

N = gets.to_i
Arr = gets.chomp.split(' ').map(&:to_i)
even = 0
odd = 0
for i in Arr
    if (i%2==0)
        even = even + 1
    else
        odd = odd + 1
    end
end

if(odd==0)
    p 0
else
    if(odd%2 == 0)
        p 2
    else
        p 1
    end
end

r = ->{gets.split.map &:to_i}
n = r[]
a = r[]
cnt = 0
for x in a
  if x % 2 == 1
    cnt += 1
  end
end
if cnt > n[0] - cnt
  ans = n[0] - cnt
else
  ans = cnt
end
p ans

n = gets.chomp
a = gets.chomp.split(' ')

odd = 0
even = 0

for u in a
    if u.to_i % 2 == 1
        odd += 1
    else
        even += 1
    end
end

if odd == 0
    puts 0
elsif even == 0
    puts odd / 3
else
    if odd > even
        puts even
    else
        puts odd
    end
end

a = gets.split

zoj = 0
fard = 0

n = a[0].to_i
b = gets.split

for i in (0..n - 1) do
	x = b[i].to_i
	if (x % 2 == 0)
	    zoj = zoj + 1
	else
	    fard = fard + 1
	end
end
if (fard > zoj)
    zoj = fard
end
puts "#{fard}"


In one school with Vasya there is a student Kostya. Kostya does not like physics, he likes different online games. Every day, having come home, Kostya throws his bag in the farthest corner and sits down at his beloved computer. Kostya even eats glued to the game. A few days ago Kostya bought a new RPG game "HaresButtle", which differs from all other games in this genre. It has a huge number of artifacts. As we know, artifacts are divided into basic and composite ones. Only the basic artifacts are available on sale. More powerful composite artifacts are collected from some number of basic artifacts.After the composing composite artifact, all the components disappear.Kostya is the head of the alliance, so he has to remember, what artifacts has not only himself, but also his allies. You must identify by sequence of artifacts purchased by Kostya and his allies, how many and which artifacts has been collected by each of them. It is believed that initially no one has any artifacts.

The first line has 4 natural numbers: k (1 ≤ k ≤ 100) — the number of Kostya's allies, n (1 ≤ n ≤ 50) — the number of basic artifacts, m (0 ≤ m ≤ 50) — the number of composite artifacts, q (1 ≤ q ≤ 500) — the number of his friends' purchases. The following n lines contain the names of basic artifacts. After them m lines contain the descriptions of composite artifacts in the following format: <Art. Name>: <Art. №1> <Art. №1 Number>, <Art. №2> <Art. №2 Number>, ... <Art. №X> <Art. №Х Number> All the numbers are natural numbers not exceeding 100 (1 ≤ X ≤ n). The names of all artifacts are different, they are composed of lowercase Latin letters, and the length of each name is from 1 to 100 characters inclusive. All the words in the format of the description of a composite artifact are separated by exactly one space. It is guaranteed that all components of the new artifact are different and have already been met in the input data as the names of basic artifacts.  Next, each of the following q lines is characterized by the number ai, the number of a friend who has bought the artifact (1 ≤ ai ≤ k), and the name of the purchased basic artifact. Let's assume that the backpacks of the heroes are infinitely large and any artifact bought later can fit in there. It is guaranteed that after the i-th purchase no more than one opportunity to collect the composite artifact appears. If such an opportunity arose, the hero must take advantage of it.

The output file should consist of k blocks. The first line should contain number bi — the number of different artifacts the i-th ally has. Then the block should contain bi lines with the names of these artifacts and the number of these artifacts. At that the lines should be printed in accordance with the lexicographical order of the names of the artifacts. In each block all the artifacts must be different, and all the numbers except the bi should be positive.

2 3 2 5
desolator
refresher
perseverance
vanguard: desolator 1, refresher 1
maelstorm: perseverance 2
1 desolator
2 perseverance
1 refresher
2 desolator
2 perseverance

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

c = Array.new(k){Hash.new{0}}

n.times do
	gets
end

h = Hash.new
m.times do
	if gets =~ /^(\w*):(.*)$/
		h[$1] = $2.split(/,/).map{|_| a, b = _.split; [a, b.to_i]}
	end
end

q.times do
	a, b = gets.split
	a = c[a.to_i - 1]
	a[b] += 1
	h.each do |k, v|
		next unless v.all?{|x, y| a[x] >= y}
		v.each do |x, y|
			a[x] -= y
		end
		a[k] += 1
	end
end

c.each do |a|
	a.reject!{|k, v| v == 0}
	p a.size
	a.to_a.sort.each do |k, v|
		puts "#{k} #{v}"
	end
end


You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).

The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters.

Print "YES" (without the quotes), if string s contains two non-overlapping substrings "AB" and "BA", and "NO" otherwise.

NoteIn the first sample test, despite the fact that there are substrings "AB" and "BA", their occurrences overlap, so the answer is "NO".In the second sample test there are the following occurrences of the substrings: BACFAB.In the third sample test there is no substring "AB" nor substring "BA".

#!/usr/bin/env ruby
s=gets.chomp
puts ((x=s.index('AB'))&&(y=s.rindex('BA'))&&y-x>1) || ((x=s.index('BA'))&&(y=s.rindex('AB'))&&y-x>1) ? :YES : :NO

# http://codeforces.com/contest/550/problem/A
def match?(s, matchers)
  a = s.clone
  matchers.all? do |w|
    b = a.clone
    a.sub!(/#{w}/, '--')

    a != b
  end
end

s = gets.chomp

puts (match?(s, %w(AB BA)) || match?(s, %w(BA AB))) ? 'YES' : 'NO'

#!/usr/bin/ruby
s = gets.chomp
2.times do
    fab = s.index('AB')
    fba = s.rindex('BA')
    s.reverse!
    s.tr!('AB', 'BA')
    next if fab.nil? || fba.nil?
    next if fab + 1 >= fba

    puts "YES"
    exit
end
puts "NO"

#!/bin/ruby

require 'json'
require 'stringio'

def twoSubstrings(str)
	if str.include?('AB') && str.include?('BA')
		tmp_str = str.split("AB", 2)
		if(tmp_str[0].include?('BA') || tmp_str[1].include?('BA'))
			return true;
		end
		tmp_str = str.split("BA", 2)
		if(tmp_str[0].include?('AB') || tmp_str[1].include?('AB'))
			return true;
		end
		return false
	else
		return false
	end
end

str = gets.rstrip

puts twoSubstrings(str) ? "YES" : "NO"

#!/bin/ruby

require 'json'
require 'stringio'

def twoSubstrings(str)
	if str.include?('AB') && str.include?('BA')
		tmp_str = str.split("AB", 2)
		return true if(tmp_str[0].include?('BA') || tmp_str[1].include?('BA'))
		tmp_str = str.split("BA", 2)
		return true if(tmp_str[0].include?('AB') || tmp_str[1].include?('AB'))
		return false
	else
		return false
	end
end

str = gets.rstrip

puts twoSubstrings(str) ? "YES" : "NO"

a=gets.chomp

if a.length>3
	i=0
	ab=0
	ba=0
	abab=0
	loop do
		if a[i..i+2]=="ABA" || a[i..i+2]=="BAB"
		abab+=1
		i+=2
		elsif a[i..i+1]=="AB"
		ab+=1
		i+=1
		elsif a[i..i+1]=="BA"
		ba+=1
		i+=1
		end
		i+=1
		break if i==a.length
		break if abab>1
		break if ab>0 && ba>0
		break if (abab>0 && ba>0) || (abab>0 && ab>0)

	end
    if ab>0 && ba>0
	puts "YES"
	elsif (abab>0 && ba>0) || (abab>0 && ab>0)
	puts "YES"
	elsif abab>1
	puts "YES"
	else
	puts "NO"
	end
else

	puts "NO"

end

# http://codeforces.com/contest/550/problem/A

def get_input
  gets.chomp
end

def result(sub1_found_idxs, sub1_length, sub2_found_idxs, sub2_length)
  return false if sub1_found_idxs.empty? || sub2_found_idxs.empty?

  case1 = sub1_found_idxs.first < sub2_found_idxs.last &&
          (sub2_found_idxs.last - sub1_found_idxs.first) >= sub1_length
  case2 = sub1_found_idxs.last > sub2_found_idxs.first &&
          (sub1_found_idxs.last - sub2_found_idxs.first) >= sub2_length

  case1 || case2
end

# Checking str contains both sub1 and sub2 without overlapping in general
def contain_substrings?(str, sub1, sub2)
  sub1_length = sub1.size
  sub2_length = sub2.size
  start_idx_sub1 = 0
  start_idx_sub2 = 0
  sub1_found_idxs = []
  sub2_found_idxs = []

  0.upto(str.size - 1) do |current_idx|
    # Find all indexes of sub1 in str
    if str[start_idx_sub1..current_idx] == sub1
      sub1_found_idxs << start_idx_sub1
      start_idx_sub1 = current_idx + 1
    elsif current_idx - start_idx_sub1 >= sub1_length - 1
      start_idx_sub1 += 1
    end

    # Find all indexes of sub2 in str
    if str[start_idx_sub2..current_idx] == sub2
      sub2_found_idxs << start_idx_sub2
      start_idx_sub2 = current_idx + 1
    elsif current_idx - start_idx_sub2 >= sub2_length - 1
      start_idx_sub2 += 1
    end
  end

  result(sub1_found_idxs, sub1_length, sub2_found_idxs, sub2_length) ? 'YES' : 'NO'
end

# puts contain_substrings?('ABA', 'AB', 'BA') => NO
# puts contain_substrings?('BACFAB', 'AB', 'BA') => YES
# puts contain_substrings?('AXBYBXA', 'AB', 'BA') => NO

puts contain_substrings?(get_input, 'AB', 'BA')

s=gets.chomp
x=s.index("AB")
y=s.rindex("BA")

if x==nil || y==nil then
	puts "NO"
elsif (x-y).abs>1 then
	puts "YES"
else
	x=s.rindex("AB")
	y=s.index("BA")
	if x==nil || y==nil then
		puts "NO"
	elsif (x-y).abs>1 then
		puts "YES"
	else
		puts "NO"
	end
end

strings = gets.strip

def solve(strings)
  i = 0
  while i < strings.size
    if strings[i..i+1] == 'AB'
      i += 2
      while i < strings.size
        if strings[i..i+1] == 'BA'
          puts 'YES'
          return
        end
        i += 1
      end
    end
    i += 1
  end
  i = 0
  while i < strings.size
    if strings[i..i+1] == 'BA'
      i += 2
      while i < strings.size
        if strings[i..i+1] == 'AB'
          puts 'YES'
          return
        end
        i += 1
      end
    end
    i += 1
  end
  puts 'NO'
end

solve(strings)

str=gets.chomp

puts ((a=str.index('AB')) and (b=str.rindex('BA')) and b-a>1) || ((a=str.index('BA')) and (b=str.rindex('AB')) and b-a>1) ? 'YES' : 'NO'

s=gets.chomp.to_s
def func(s,c,d)
	y=s
	$~=nil
	y=y.sub(/#{c}/,'x')
	#puts "HEY #{$~}"
	#puts y
	if $~
		$~=nil
		y=y.sub(/#{d}/,'x')
		#puts "BYE #{$~}"
		#puts y
		if $~
			return true
		else
			return false
		end
	else
		return false
	end
end

if func(s,'AB','BA') || func(s,'BA','AB')
	print("YES\n")
else
	puts "NO"
end

str = gets.chomp

def occurences(str)
  flag = false

  str.each_char.each_with_index.inject([]) do |result, (c, index)|
    if c == 'A'
      flag = true
    elsif c == 'B' && flag
      result << index - 1
      flag = false
    else
      flag = false
    end

    result
  end
end

array = occurences(str)
reverse_array = occurences(str.reverse).map do |item|
  str.size - item - 1
end.sort

result = nil

array.each do |item|
  result = reverse_array.find do |other_item|
    (other_item - item > 2) || (other_item < item)
  end

  if result
    break
  end
end

if result.nil? || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

s=gets.to_s
if s.index('AB').nil? || s.index('BA').nil?
  puts :NO
else
  puts (s.rindex('AB')-s.index('BA')>1||s.rindex('BA')-s.index('AB')>1)?:YES: :NO
end

input = gets.chomp

def val(input)
  ab_index = []
  ba_index = []
  i = 0
  while i < input.length - 1
    ab_index << i if input[i..i + 1] == 'AB'
    i += 1
  end

  i = input.length - 1
  while i >= 0
    ba_index << i if input[i..i + 1] == 'BA'
    i -= 1
  end

  if !ba_index.first.nil? &&
     !ab_index.first.nil? &&
     (ba_index.first - ab_index.first > 1 ||
      ab_index.last - ba_index.last > 1)
    puts 'YES'
    return
  end

  puts 'NO'
end

val(input)

n = gets.chomp.split("")

count = 0

if n.size > 3
	arr = []
	arr1 = []
	for i in (0..n.size-1)
		if n[i] == "A" && n[i+1] == "B"
			arr << [[i,i+1], "AB"]
		end
	end
	i = n.size-1
	while i > 0
		if n[i] == "A" && n[i-1] == "B"
			arr1 << [[i-1,i], "BA"]
		end
		i -= 1
	end

	if arr.size > 0 && arr1.size > 0
		if arr.size <= arr1.size
			for i in (0..arr.size-1)
				for x in (0..arr1.size-1)
					if arr[i][0][0] != arr1[x][0][0] && arr[i][0][1] != arr1[x][0][0] && arr[i][0][0] != arr1[x][0][1] && arr[i][0][1] != arr1[x][0][1]
						count += 1
						break
					end
				end
			end
		else
			for i in (0..arr1.size-1)
				for x in (0..arr.size-1)
					if arr1[i][0][0] != arr[x][0][0] && arr1[i][0][1] != arr[x][0][0] && arr1[i][0][0] != arr[x][0][1] && arr1[i][0][1] != arr[x][0][1]
						count += 1
						break
					end
				end
			end
		end
	end
end

if count > 0
	print 'YES'
else
	print 'NO'
end

input = gets.chomp
input_copy = input

a = input.index("AB")
b = input.index("BA")

if a != nil
  input = input[0,a] + "XX" + input[a+2,input.length]
  if input.index("BA") != nil
    puts("YES")
    exit(0)
  end
end

input = input_copy

if b != nil
  input = input[0,b] + "XX" + input[b+2,input.length]
  if input.index("AB") != nil
    puts("YES")
    exit(0)
  end
end

puts("NO")

def solution(string)
  return "NO" if string.index("AB").nil? || string.index("BA").nil?
  return "YES" if (string.rindex("AB") - string.index("BA")).abs != 1
  return "YES" if (string.rindex("BA") - string.index("AB")).abs != 1
  "NO"
end
puts solution(gets.strip)

# http://codeforces.com/contest/550/problem/A
s = gets.chomp

n = s.length
l_ab, l_ba, r_ab, r_ba = 0, 0, n - 1, n - 1

while l_ab < n - 1 && r_ba >= 1
  first = s[l_ab] + s[l_ab + 1]
  last = s[r_ba - 1] + s[r_ba]

  if first == "AB"
    break if last == "BA"
    r_ba -= 1
  else
    l_ab += 1
  end
end

while l_ba < n - 1 && r_ab >= 1
  first = s[l_ba] + s[l_ba + 1]
  last = s[r_ab - 1] + s[r_ab]

  if first == "BA"
    break if last == "AB"
    r_ab -= 1
  else
    l_ba += 1
  end
end

puts (r_ba - l_ab - 1 > 1) || (r_ab - l_ba - 1 > 1) ? "YES" : "NO"

s = gets
d = s.dup

if s.sub!('AB', 'XX').nil? || d.sub!('BA', 'XX').nil?
  puts 'NO'
elsif (s && s.sub!('BA', 'XX')) || (d && d.sub!('AB', 'XX'))
  puts 'YES'
else
  puts 'NO'
end

# http://codeforces.com/contest/550/problem/A
s = gets.chomp

flag = %w(AB BA).all? do |w|
  old = s.clone
  s.gsub!(/#{w}/, '')

  (s.length != old.length) && ((old.length - s.length) % 2).even?
end

puts flag ? 'YES' : 'NO'

# http://codeforces.com/contest/550/problem/A
s = gets.chomp

flag = %w(AB BA).all? do |w|
  old = s.clone
  s.sub!(/#{w}/, '')

  (s.length != old.length) && ((old.length - s.length) % 2).even?
end

puts flag ? 'YES' : 'NO'

# http://codeforces.com/contest/550/problem/A
def match?(s, matchers)
  a = s.clone
  matchers.all? do |w|
    b = a.clone
    a.sub!(/#{w}/, '')

    b.length - a.length == w.length
  end
end

s = gets.chomp
puts (match?(s, %w(AB BA)) || match?(s, %w(BA AB))) ? 'YES' : 'NO'

# http://codeforces.com/contest/550/problem/A
s = gets.chomp

flag = %w(AB BA).all? do |w|
  s2 = s.delete(w)

  return false if s2.length == s.length
  ((s2.length - s.length) % 2).even?
end

puts flag ? 'YES' : 'NO'

#!/usr/bin/ruby
s = gets.chomp
2.times do
    s.reverse!
    fab = s.index('AB')
    fba = s.rindex('BA')
    next if fab.nil? || fba.nil?
    next if fab + 1 >= fba

    puts "YES"
    exit
end
puts "NO"

#!/bin/ruby

require 'json'
require 'stringio'

def twoSubstrings(str)
	if str.include?('AB') && str.include?('BA')
		tmp_str = str.split("AB", 2)
		return false unless (tmp_str[0].include?('BA') || tmp_str[1].include?('BA'))
		tmp_str = str.split("BA", 2)
		return false unless (tmp_str[0].include?('AB') || tmp_str[1].include?('AB'))
		return true
	else
		return false
	end
end

str = gets.rstrip

puts twoSubstrings(str) ? "YES" : "NO"

#!/bin/ruby

require 'json'
require 'stringio'

def twoSubstrings(str)
	if str.include?('AB') && str.include?('BA')
		tmp_str = str.split("AB", 2)
		return false unless (tmp_str[0].include?('BA') || tmp_str[1].include?('BA'))
		tmp_str = str.split("BA", 2)
		return false unless (tmp_str[0].include?('AB') || tmp_str[1].include?('AB'))
		return true
	else
		return false
	end
end

str = gets.rstrip

puts twoSubstrings str

#!/bin/ruby

require 'json'
require 'stringio'

def twoSubstrings(str)
	return false if str.include?('ABA')
	if str.include?('AB') && str.include?('BA')
		tmp_str = str.split("AB", 2)
		return false unless (tmp_str[0].include?('BA') || tmp_str[1].include?('BA'))
		tmp_str = str.split("BA", 2)
		return false unless (tmp_str[0].include?('AB') || tmp_str[1].include?('AB'))
		return true
	else
		return false
	end
end

str = gets.rstrip

puts twoSubstrings(str) ? "YES" : "NO"

a=gets.chomp

if a.length>3
	i=0
	ab=0
	ba=0
	abab=0
	loop do
		if a[i..i+2]=="ABA" || a[i..i+2]=="BAB"
		abab+=1
		i+=2
		elsif a[i..i+1]=="AB"
		ab+=1
		i+=1
		elsif a[i..i+1]=="BA"
		ba+=1
		i+=1
		end
		i+=1
		break if i==a.length
		break if abab>1
		break if ab>0 && ba>0
		break if (abab>0 && ba>0) || (abab>0 && ab>0)

	end
    if ab>0 && ba>0
	puts "YES"
	elsif (abab>0 && ba>1) || (abab>0 && ab>1)
	puts "YES"
	else
	puts "NO"
	end
else

	puts "NO"

end

a=gets.chomp

if a.length>3
	i=0
	ab=0
	ba=0
	abab=0
	loop do
		if a[i..i+2]=="ABA" || a[i..i+2]=="BAB"
		abab+=1
		i+=2
		elsif a[i..i+1]=="AB"
		ab+=1
		i+=1
		elsif a[i..i+1]=="BA"
		ba+=1
		i+=1
		end
		i+=1
		break if i==a.length
		break if abab>1
		break if ab>0 && ba>0
		break if (abab>0 && ba>0) || (abab>0 && ab>0)

	end
    if ab>0 && ba>0
	puts "YES"
	elsif (abab>0 && ba>1) || (abab>0 && ab>1)
	puts "YES"
	elsif abab>1
	puts "YES"
	else
	puts "NO"
	end
else

	puts "NO"

end

a=gets.chomp
i=0
f=0
p="ab"
loop do
if p=="ab"

	if a[i..i+1]=="AB" || a[i..i+1]=="BA"
		if a[i..i+1]=="AB"
		p="b"
		else
		p="a"
		end
	f+=1
	i+=1
	end
elsif  p=="a"

	if a[i..i+1]=="AB"
	f+=1
	i+=1
	p="b"
	end
elsif p=="b"

	if a[i..i+1]=="BA"
	f+=1
	i+=1
	end
end
	i+=1
	break if i==a.length
end

if f==2
puts "YES"
else
puts "NO"
end

a=gets.chomp

if a.length>3
	i=0
	ab=0
	ba=0
	abab=0
	loop do
		if a[i..i+2]=="ABA" || a[i..i+2]=="BAB"
		abab+=1
		end
		if a[i..i+1]=="AB"
		ab+=1
		i+=1
		elsif a[i..i+1]=="BA"
		ba+=1
		i+=1
		end
		i+=1
		break if i==a.length
		break if abab>1
		break if ab>0 && ba>0
		break if (abab>0 && ba>1) || (abab>0 && ab>1)

	end
    if ab>0 && ba>0
	puts "YES"
	elsif (abab>0 && ba>1) || (abab>0 && ab>1)
	puts "YES"
	else
	puts "NO"
	end
else

	puts "NO"

end

# http://codeforces.com/contest/550/problem/A

def get_input
  gets.chomp
end

# Checking str contains both sub1 and sub2 without overlapping in general
def contain_substrings?(str, sub1, sub2)
  sub1_length = sub1.size
  sub2_length = sub2.size
  start_idx_sub1 = 0
  start_idx_sub2 = 0
  sub1_found_idxs = []
  sub2_found_idxs = []

  0.upto(str.size - 1) do |current_idx|
    # Find all indexes of sub1 in str
    if str[start_idx_sub1..current_idx] == sub1
      sub1_found_idxs << start_idx_sub1
      start_idx_sub1 = current_idx + 1
    elsif current_idx - start_idx_sub1 >= sub1_length - 1
      start_idx_sub1 += 1
    end

    # Find all indexes of sub2 in str
    if str[start_idx_sub2..current_idx] == sub2
      sub2_found_idxs << start_idx_sub2
      start_idx_sub2 = current_idx + 1
    elsif current_idx - start_idx_sub2 >= sub2_length - 1
      start_idx_sub2 += 1
    end
  end

  if sub1_found_idxs.empty? || sub2_found_idxs.empty?
    'NO'
  elsif sub1_found_idxs.first < sub2_found_idxs.last
    sub2_found_idxs.last - sub1_found_idxs.first >= sub1_length ? 'YES' : 'NO'
  elsif sub1_found_idxs.last > sub2_found_idxs.first
    sub1_found_idxs.last - sub2_found_idxs.first >= sub2_length ? 'YES' : 'NO'
  else
    'NO'
  end
end

# puts contain_substrings?('ABA', 'AB', 'BA') => NO
# puts contain_substrings?('BACFAB', 'AB', 'BA') => YES
# puts contain_substrings?('AXBYBXA', 'AB', 'BA') => NO

puts contain_substrings?(get_input, 'AB', 'BA')

# http://codeforces.com/contest/550/problem/A

def get_input
  gets.chomp
end

def result(sub1_found_idxs, sub1_length, sub2_found_idxs, sub2_length)
  return 'NO' if sub1_found_idxs.empty? || sub2_found_idxs.empty?

  case1 = sub1_found_idxs.first < sub2_found_idxs.last &&
          (sub2_found_idxs.last - sub1_found_idxs.first) >= sub1_length
  case2 = sub1_found_idxs.last > sub2_found_idxs.first &&
          (sub1_found_idxs.last - sub2_found_idxs.first) >= sub2_length

  case1 || case2
end

# Checking str contains both sub1 and sub2 without overlapping in general
def contain_substrings?(str, sub1, sub2)
  sub1_length = sub1.size
  sub2_length = sub2.size
  start_idx_sub1 = 0
  start_idx_sub2 = 0
  sub1_found_idxs = []
  sub2_found_idxs = []

  0.upto(str.size - 1) do |current_idx|
    # Find all indexes of sub1 in str
    if str[start_idx_sub1..current_idx] == sub1
      sub1_found_idxs << start_idx_sub1
      start_idx_sub1 = current_idx + 1
    elsif current_idx - start_idx_sub1 >= sub1_length - 1
      start_idx_sub1 += 1
    end

    # Find all indexes of sub2 in str
    if str[start_idx_sub2..current_idx] == sub2
      sub2_found_idxs << start_idx_sub2
      start_idx_sub2 = current_idx + 1
    elsif current_idx - start_idx_sub2 >= sub2_length - 1
      start_idx_sub2 += 1
    end
  end

  result(sub1_found_idxs, sub1_length, sub2_found_idxs, sub2_length) ? 'YES' : 'NO'
end

# puts contain_substrings?('ABA', 'AB', 'BA') => NO
# puts contain_substrings?('BACFAB', 'AB', 'BA') => YES
# puts contain_substrings?('AXBYBXA', 'AB', 'BA') => NO

puts contain_substrings?(get_input, 'AB', 'BA')

s=gets.chomp
x=s.index("AB")
y=s.rindex("BA")
if x==nil || y==nil then
	puts "NO"
elsif (x-y).abs>1 then
	puts "YES"
else
	puts "NO"
end

strings = gets.strip

ab = nil
ba = nil

i = 0

yes = false
while i < strings.size
  if !ab && strings[i..i+1] == 'AB' && ([i, i+1]&ba.to_a).empty?
    ab = [i, i+1]
  elsif !ba && strings[i..i+1] == 'BA' && ([i, i+1]&ab.to_a).empty?
    ba = [i, i+1]
  end

  if ab && ba && (ab&ba).empty?
    yes = true
    break
  end

  i += 1
end

puts yes ? 'YES' : 'NO'

strings = gets.strip

ab = nil
ba = nil

i = 0

yes = false
while i < strings.size
  if strings[i..i+1] == 'AB' && ([i, i+1]&ba.to_a).empty?
    ab = [i, i+1]
  elsif strings[i..i+1] == 'BA' && ([i, i+1]&ba.to_a).empty?
    ba = [i, i+1]
  end

  if ab && ba && (ab&ba).empty?
    yes = true
    break
  end

  i += 1
end

puts yes ? 'YES' : 'NO'

strings = gets.strip

ab = nil
ba = nil

i = 0

while i < strings.size
  ab = [i, i+1] if strings[i..i+1] == 'AB'
  ba = [i, i+1] if strings[i..i+1] == 'BA'
  break if ab && ba
  i += 1
end

puts ab && ba && (ab&ba).empty? ? 'YES' : 'NO'

strings = gets.strip

flags = 0
strings.each_char do |c|
  flags ^= 1 << c.ord - 65
end

count = 0
while flags != 0
  flags &= flags - 1
  count += 1
end

puts count > 1 ? 'YES' : 'NO'

strings = gets.strip

def solve(strings)
  i = 0
  while i < strings.size
    if strings[i..i+1] == 'AB'
      i += 2
      while i < strings.size
        if strings[i..i+1] == 'BA'
          puts 'YES'
          return
        end
        i += 1
      end
    elsif strings[i..i+1] == 'BA'
      i += 2
      while i < strings.size
        if strings[i..i+1] == 'AB'
          puts 'YES'
          return
        end
        i += 1
      end
    end
    i += 1
  end
  puts 'NO'
end

solve(strings)

strings = 'AXBYBXA'

flags = 0
strings.each_char do |c|
  flags ^= 1 << c.ord - 65
end

count = 0
while flags != 0
  flags &= flags - 1
  count += 1
end

puts count > 1 ? 'YES' : 'NO'

str=gets.chomp

puts ((a=str.index('AB')) and (b=str.index('BA')) and b-a>1) || ((a=str.index('BA')) and (b=str.rindex('AB')) and b-a>1) ? 'YES' : 'NO'

s=gets.chomp.to_s
s=s.sub(/AB/,'')
puts s
unless $~
	puts "NO"
else
	s=s.sub(/BA/,'')
	puts s
	unless $~
		puts ("NO")
	else
		puts "YES"
	end
end

s=gets.chomp.to_s
def func(s,c,d)
	y=s
	y=y.sub(/#{c}/,'')
	if $~
		y=y.sub(/#{d}/,'')
		if $~
			return true
		else
			return false
		end
	else
		return false
	end
end

if func(s,'AB','BA') || func(s,'BA','AB')
	print("YES\n")
else
	puts "NO"
end

s=gets.chomp.to_s
s=s.sub(/AB/,'')
#puts s
unless $~
	puts "NO"
else
	s=s.sub(/BA/,'')
	#puts s
	unless $~
		puts ("NO")
	else
		puts "YES"
	end
end

str = gets.chomp

flag = false
array = []

str.each_char.each_with_index do |c, index|
  if c == 'A'
    flag = true
  elsif c == 'B' && flag
    array << index - 1
  else
    flag = false
  end
end

reverse_array = []
flag = false
size = str.size

str.reverse.each_char.each_with_index do |c, index|
  if c == 'A'
    flag = true
  elsif c == 'B' && flag
    reverse_array << size - index
  else
    flag = false
  end
end

result = nil

array.each do |item|
  result = reverse_array.bsearch { |other_item| other_item > item && other_item - item < 3 }

  if result
    break
  end
end

if result || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

str = gets.chomp

def occurences(str)
  flag = false

  str.each_char.each_with_index.inject([]) do |result, (c, index)|
    if c == 'A'
      flag = true
    elsif c == 'B' && flag
      result << index - 1
    else
      flag = false
    end

    result
  end
end

array = occurences(str)
reverse_array = occurences(str.reverse).map do |item|
  str.size - item - 1
end.sort

result = nil

puts "#{array} #{reverse_array}"
array.each do |item|
  result = reverse_array.bsearch { |other_item| (other_item - item).abs > 2 }

  if result
    break
  end
end

if result.nil? || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

str = gets.chomp

def occurences(str)
  flag = false

  str.each_char.each_with_index.inject([]) do |result, (c, index)|
    if c == 'A'
      flag = true
    elsif c == 'B' && flag
      result << index - 1
    else
      flag = false
    end

    result
  end
end

array = occurences(str)
reverse_array = occurences(str.reverse).map do |item|
  str.size - item - 1
end.sort

result = nil

array.each do |item|
  result = reverse_array.bsearch do |other_item|
    (other_item - item > 2) || (other_item < item)
  end

  if result
    break
  end
end

if result.nil? || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

str = gets.chomp

def occurences(str)
  flag = false

  str.each_char.each_with_index.inject([]) do |result, (c, index)|
    if c == 'A'
      flag = true
    elsif c == 'B' && flag
      result << index - 1
    else
      flag = false
    end

    result
  end
end

array = occurences(str)
reverse_array = occurences(str.reverse).map do |item|
  str.size - item - 1
end.sort

result = nil

array.each do |item|
  result = reverse_array.bsearch { |other_item| (other_item - item).abs > 2 }

  if result
    break
  end
end

if result.nil? || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

str = gets.chomp

def occurences(str)
  flag = false

  str.each_char.each_with_index.inject([]) do |result, (c, index)|
    if c == 'A'
      flag = true
    elsif c == 'B' && flag
      result << index - 1
      flag = false
    else
      flag = false
    end

    result
  end
end

array = occurences(str)
reverse_array = occurences(str.reverse).map do |item|
  str.size - item - 1
end.sort

result = nil

array.each do |item|
  result = reverse_array.bsearch do |other_item|
    (other_item - item > 2) || (other_item < item)
  end

  if result
    break
  end
end

if result.nil? || array.empty? || reverse_array.empty?
  puts 'NO'
else
  puts 'YES'
end

input = 'AXBYBXA'

def validate(input)
  return false unless input.include?('AB') && input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 2
    if input[index..index + 1] == 'AB' || input[index..index + 1] == 'BA'
      # back and forward word should not overlap

      unless input[index..index + 2] == 'ABA' ||
             input[index..index + 2] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA'
        return true
      end
    end
  end

  true
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

input = gets.chomp

def validate(input)
  return false unless input.include?('AB') || input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 1
    if input[index..index + 1] == 'AB' || input[index..index + 1] == 'BA'
      # back and forward word should not overlap

      unless input[index..index + 2] == 'ABA' ||
             input[index..index + 2] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA'
        return true
      end
    end
  end

  true
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

input = gets.chomp

def validate(input)
  return false unless input.include?('AB') || input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 1
    if input[index..index + 1] == 'AB' || input[index..index + 1] == 'BA'
      # back and forward word should not overlap

      unless input[index..index + 2] == 'ABA' ||
             input[index..index + 2] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA'
        return true
      end
    end
  end

  false
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

def read
  #gets.chomp
  'ABAAB'
end

def validate
  input = read
  return false unless input.include?('AB') || input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 3
    if input[index..index + 2] == 'ABA' || input[index..index + 2] == 'BAB'
      return false
    end
  end

  true
end

def output
  if validate
    puts 'YES'
  else
    puts 'NO'
  end
end

output

input = gets.chomp

def validate(input)
  return false unless input.include?('AB') || input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 1
    if input[index..index + 1] == 'AB' || input[index..index + 1] == 'BA'
      # back and forward word should not overlap

      puts input[index..index + 1]
      unless input[index..index + 2] == 'ABA' ||
             input[index..index + 2] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA'
        return true
      end
    end
  end

  false
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

def read
  gets.chomp
end

def validate
  input = read
  return false unless input.include?('AB') || input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 3
    if input[index..index + 3] == 'ABA' || input[index..index + 3] == 'BAB'
      return false
    end
  end

  true
end

def output
  if validate
    puts 'YES'
  else
    puts 'NO'
  end
end

output

input = gets.chomp

def val(input)
  ab_index = []
  ba_index = []
  i = 0
  while i < input.length - 1
    ab_index << i if input[i..i + 1] == 'AB'
    i += 1
  end

  i = input.length - 1
  while i >= 0
    ba_index << i if input[i..i + 1] == 'BA'
    i -= 1
  end

  if !ba_index.first.nil? &&
     !ab_index.first.nil? &&
     (ba_index.first - ab_index.first > 1 ||
      ab_index.first - ba_index.first > 1)
    puts 'YES'
    return
  end

  puts 'NO'
end

val(input)

input = gets.chomp

def val(input)
  ab_index = []
  ba_index = []
  i = 0
  while i < input.length - 1
    ab_index << i if input[i..i + 1] == 'AB'
    i += 1
  end

  i = input.length - 1
  while i >= 0
    ba_index << i if input[i..i + 1] == 'BA'
    i -= 1
  end

  if !ba_index.last.nil? &&
     !ab_index.first.nil? &&
     (ba_index.last - ab_index.first > 1 ||
      ab_index.first - ba_index.last > 1)
    puts 'YES'
    return
  end

  puts 'NO'
end

val(input)

input = 'ABAAHBA'

def validate(input)
  return false unless input.include?('AB') && input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 2
    if input[index..index + 1] == 'AB' || input[index..index + 1] == 'BA'
      # back and forward word should not overlap

      unless input[index..index + 2] == 'ABA' ||
             input[index..index + 2] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA' ||
             input[index - 1..index + 1] == 'ABA'
        return true
      end
    end
  end

  false
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

input = gets.chomp

def validate(input)
  return false unless input.include?('AB') && input.include?('BA')
  input.each_char.with_index do |_, index|
    break if index > input.length - 3
    if input[index..index + 2] == 'ABA' || input[index..index + 2] == 'BAB'
      return false
    end
  end

  true
end

def output(input)
  if validate(input)
    puts 'YES'
  else
    puts 'NO'
  end
end

output(input)

n = gets.chomp.split("")

ab = 0
ba = 0

while n.size > 1 || (ab > 0 && ba > 0)
	if n.index("A") != nil && n.index("B") != nil && n.index("A") == n.index("B")-1 && n.size >= 2
		ab += 1
		n.delete_at(n.index("A"))
		n.delete_at(n.index("B"))
	elsif n.index("A") != nil && n.index("B") != nil && n.index("B") == n.index("A")-1 && n.size >= 2
		ba += 1
		n.delete_at(n.index("B"))
		n.delete_at(n.index("A"))
	else
		break
	end
end
if ab > 0 && ba > 0
	print "YES"
else
	print "NO"
end

n = gets.chomp.split("")

count = 0

if n.size > 3
	arr = []
	arr1 = []
	for i in (0..n.size-1)
		if n[i] == "A" && n[i+1] == "B"
			arr << [i+1, "AB"]
		end
	end
	i = n.size-1
	while i > 1
		if n[i] == "A" && n[i-1] == "B"
			arr1 << [i-1, "BA"]
		end
		i -= 1
	end

	if arr.size > 0 && arr1.size > 0
		if arr.size <= arr1.size
			for i in (0..arr.size-1)
				for x in (0..arr1.size-1)
					if arr[i][0] != arr1[x][0]
						count += 1
						break
					end
				end
			end
		else
			for i in (0..arr1.size-1)
				for x in (0..arr.size-1)
					if arr1[i][0] != arr[x][0]
						count += 1
						break
					end
				end
			end
		end
	end
end

if count > 0
	print 'YES'
else
	print 'NO'
end

n = gets.chomp.split("")

count = 0

if n.size > 3
	arr = []
	arr1 = []
	for i in (0..n.size-1)
		if n[i] == "A" && n[i+1] == "B"
			arr << [i+1, "AB"]
		end
	end
	i = n.size-1
	while i > 0
		if n[i] == "A" && n[i-1] == "B"
			arr1 << [i, "BA"]
		end
		i -= 1
	end

	if arr.size > 0 && arr1.size > 0
		for i in (0..arr.size-1)
			if arr[i][0] != arr1[i][0]
				count += 1
				break
			end
		end
	end
end

if count > 0
	print 'YES'
else
	print 'NO'
end

n = gets.chomp.split("")

count = 0

if n.size > 3
	arr = []
	arr1 = []
	for i in (0..n.size-1)
		if n[i] == "A" && n[i+1] == "B"
			arr << [i+1, "AB"]
		end
	end
	i = n.size-1
	while i > 0
		if n[i] == "A" && n[i-1] == "B"
			arr1 << [i-1, "BA"]
		end
		i -= 1
	end

	if arr.size > 0 && arr1.size > 0
		if arr.size <= arr1.size
			for i in (0..arr.size-1)
				for x in (0..arr1.size-1)
					if arr[i][0] != arr1[x][0]
						count += 1
						break
					end
				end
			end
		else
			for i in (0..arr1.size-1)
				for x in (0..arr.size-1)
					if arr1[i][0] != arr[x][0]
						count += 1
						break
					end
				end
			end
		end
	end
end

if count > 0
	print 'YES'
else
	print 'NO'
end

input = gets.chomp
input_copy = input

a = input.index("AB")
b = input.index("BA")

if a != nil
  input = input[0,a] + input[a+2,input.length]
  if input.index("BA") != nil
    puts("YES")
    exit(0)
  end
end

input = input_copy

if b != nil
  input = input[0,b] + input[b+2,input.length]
  if input.index("AB") != nil
    puts("YES")
    exit(0)
  end
end

puts("NO")

def solution(string)
  return "NO" if string.index("AB").nil? || string.index("BA").nil?
  return "YES" if (string.rindex("AB") - string.index("BA")).abs != 1
  "NO"
end
puts solution(gets.strip)

s = gets.chomp.chars
c = [false, false]
i = 0
while c.include?(false) && i < s.size
  if s[i] == 'A' && s[i + 1] == 'B' && !c[0]
    c[0] = true
    i += 2
  elsif s[i] == 'B' && s[i + 1] == 'A' && !c[1]
    c[1] = true
    i += 2
  else
    i += 1
  end
end
puts c.all?{|x| x} ? 'YES' : 'NO'

s = gets.chomp
puts s.include?('AB') && s.include?('BA') && !s.include?('ABA') && !s.include?('BAB') ? 'YES' : 'NO'

s = gets.chomp.chars
c = [false, false]
i = 0
while c.include?(false) && i < s.size
  if s[i] == 'A' && s[i + 1] == 'B'
    c[0] = true
    i += 2
  elsif s[i] == 'B' && s[i + 1] == 'A'
    c[1] = true
    i += 2
  else
    i += 1
  end
end
puts c.all?{|x| x} ? 'YES' : 'NO'

s = gets.chomp
puts s.slice!('AB') && s.slice!('BA') ? 'YES' : 'NO'

s = gets.chomp
puts (s.slice!('AB') && s.slice!('BA')) || (s.slice!('BA') && s.slice!('AB')) ? 'YES' : 'NO'

# http://codeforces.com/contest/550/problem/A

s = gets.chomp

n = s.length
l, r = 0, n - 1

while l < n - 1
  first = s[l] + s[l + 1]
  if first == "AB" || first == "BA"
    break l
  else
    l += 1
  end
end

while r >= 1
  last = s[r] + s[r - 1]
  if last == "AB" || last == "BA"
    break r -= 1
  else
    r -= 1
  end
end

puts r - l > 1 ? "YES" : "NO"

# http://codeforces.com/contest/550/problem/A
s = gets.chomp

n = s.length
l, r = 0, n - 1

while l < n - 1 && r >= 1
  first = s[l] + s[l + 1]
  last = s[r - 1] + s[r]
  if first == "AB"
    break if last == "BA"
    r -= 1
  elsif first == "BA"
    break if last == "AB"
    r -= 1
  else
    l += 1
  end
end

puts r - l - 1 > 1 ? "YES" : "NO"

s = gets
d = s.dup

if s.sub!('AB', '').nil? || d.sub!('BA', '').nil?
  puts 'NO'
elsif (s && s.sub!('BA', '')) || (d && d.sub!('AB', ''))
  puts 'YES'
else
  puts 'NO'
end

begin
  throw 'Error' if gets.sub!('AB', '').sub!('BA', '').nil?
  puts 'YES'
rescue
  puts 'NO'
end