Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.

The input consists of only two strings s and t denoting the favorite Santa's patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.

If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes). Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct. If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair. Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.

original = gets.chomp
altered = gets.chomp

mapping = {}
fixable = true

original.size.times do |i|
  a = original[i]
  b = altered[i]

  if (mapping[b] && mapping[b] != a) || (mapping[a] && mapping[a] != b)
    fixable = false
  else
    mapping[a] = b
    mapping[b] = a
  end
end

if fixable
  has_key = {}
  ans = {}
  mapping.each do |key, value|
    ans[key] = value unless has_key[key] || key == value
    has_key[key] = true
    has_key[value] = true
  end

  puts ans.length
  ans.each do |key, value|
    puts "#{key} #{value}"
  end

else
  puts "-1"
end

a = gets
b = gets
vis = {}
res = []
fin = true
for i in 0..(a.size() - 2)
  if ((vis.include?(a[i]) || vis.include?(b[i])))
      if (!(vis.include?a[i]) || !(vis.include?b[i]) || vis[a[i]] != b[i])
          puts -1
          fin = false
          break
      end
  end
   next if (vis.include?(a[i]))
   vis[a[i]] = b[i]
   vis[b[i]] = a[i]
   if (a[i] != b[i])
       res.push([a[i],b[i]])
   end
end
if (fin)
    puts res.size()
    for i in res
        puts "#{i[0]} #{i[1]}"
    end
end

original = gets.chomp
altered = gets.chomp

mapping = {}
fixable = true

original.size.times do |i|
  if mapping[original[i]]
    fixable = false unless mapping[original[i]] == altered[i]
  else
    mapping[original[i]] = altered[i]
  end
end

if fixable
  has_key = {}
  ans = {}
  mapping.each do |key, value|
    ans[key] = value unless has_key[key] || key == value
    has_key[key] = true
    has_key[value] = true
  end

  puts ans.length
  ans.each do |key, value|
    puts "#{key} #{value}"
  end

else
  puts "-1"
end


A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).  Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of dice in the tower. The second line contains an integer x (1 ≤ x ≤ 6) — the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≤ ai, bi ≤ 6; ai ≠ bi) — the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.

Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).

n = gets.to_i
t = gets.to_i
a = Array.new(n){
    b = gets.split.map(&:to_i)
    [*1..6] - b - b.map{|_| 7 - _}
}
puts a.uniq.size == 1 ? :YES : :NO

RD =->{gets.to_i}
I =->{gets.split.map &:to_i}

def solve
	n = RD[]; t1 = RD[]; t2 = 7 - t1; n.times{
		a, b = I[]
		return "NO" if a == t1 || a == t2 || b == t1 || b == t2
	}
	return "YES"
end

puts solve

gets
$u=gets.hex
puts gets(p)=~/[#$u#{7-$u}]/?"NO":"YES"

def solve(x, faces)
  faces.each do |a, b|
    if (a == b) or (a == x) or (b == x) or ((a + b) == 7) or ((a + x) == 7) or ((b + x) == 7)
      return false
    end
  end
  true
end

n = gets.chomp.to_i
x = gets.chomp.to_i
faces = []
n.times do
  faces << gets.chomp.split(" ").map{|e| e.to_i}
end

ret = solve(x, faces)
puts ret ? "YES" : "NO"

n = gets.to_i - 1
x = 7 - gets.to_i
gets
n.times do
  a = gets.split.map(&:to_i)
  g = ([1,2,3,4,5,6] - [a[0], 7-a[0], a[1], 7-a[1], 7-x])
  if g.size == 1
    x = g[0]
  else
    puts :NO
    exit
  end
end
puts :YES

def r() gets.to_s.split.map &:to_i end
n,x,o=*r,*r;
n.times do
  a,b=*r;o||=[a,b,7-a,7-b].include? x
end
print o ? "NO" : "YES"

#!/usr/bin/ruby
n = gets.to_i
top = gets.to_i
a = []
n.times do
  a << gets.split.map {|x| x.to_i}
end
ans = "YES"
sum = 1 + 2 + 3 + 4 + 5 + 6
for i in 0...n do
  t = sum - top - a[i][0] - a[i][1] - (7 - a[i][0]) - (7 - a[i][1])
  if t == a[i][0] || t == a[i][1] || t == (7 - a[i][0]) || t == (7 - a[i][1]) then
    ans = "NO"
    break
  end
end
puts ans

n = gets.to_i
top = gets.to_i
bottom = 7 - top.to_i
sides = []
flag = true
n.times do |i|
    side1, side2 = gets.chomp.split.map(&:to_i)
    if side1 == top || side1 == bottom || side2 == top ||side2 == bottom then
        flag = false
    end
end
puts flag ? "YES" : "NO"

n = gets.to_i
last = gets.to_i
1.upto(n) {
    buf = gets.split(" ")
    a = buf[0].to_i
    b = buf[1].to_i
    if a == last || b == last || a == 7 - last || b == 7 - last
        print "NO"
        exit 0
    end
}
print "YES"

n = gets.to_i
top = gets.to_i
(1..n).each do
    left, right = gets.split.collect{|i| i.to_i}
    if left == top or 7-left == top or\
       right == top or 7-right == top
        puts 'NO'
        exit
    end
end
puts 'YES'

n = gets.to_i
c = 7 - gets.to_i
n.times do
  c = 7 - c
  a,b = gets.split.map &:to_i
  if a==c || a==7-c || b==7-c || b == c
    puts 'NO'
    exit
  end
end
puts "YES"

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

n = gets.to_i
d = gets.to_i
for _ in 1..n
  a = read_next_line
  a.concat(a.map { |x| 7 - x })
  if a.include? d
    puts 'NO'
    exit
  end
end
puts 'YES'

gets
u = gets.to_i
puts gets(p) =~ /[#{u}#{7-u}]/ ? "NO" : "YES"

n=gets.to_i
u=gets.to_i
d=7-u
gets
(n-1).times{
	unless gets.split.map(&:to_i)&[u,d]==[]
		puts "NO"
		exit
	end
}
puts "YES"

n = gets.to_i
last = gets.to_i
1.upto(n) {
    buf = gets.split(" ")
    a = buf[0].to_i
    b = buf[1].to_i
    if a == last || b == last
        print "NO"
        exit 0
    end
    last = 7 - last
}
print "YES"

n = gets.to_i
c = 7 - gets.to_i
n.times do
  c = 7 - c
  a,b = gets.split.map &:to_i
  if a==c || b == c
    puts 'NO'
    exit
  end
end
puts "YES"


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

cal = gets.split(' ').map(&:to_i).unshift(0)
ans = 0
gets.split(//).map(&:to_i).each{|x| ans += cal[x]}
puts ans

a = gets.split.map(&:to_i)
b = gets.chomp.to_s
b = b.each_char.map(&:to_i)
sum = 0

for i in 0..b.length-1
    sum += a[b[i]-1]
end
puts sum

a,b,c,d = gets.split.map(&:to_i)
s = gets.chomp.to_s.split(//)
sum = 0
s.each {
    |i|
    if i == '1'
        sum+=a
    elsif i == '2'
        sum+=b
    elsif i == '3'
        sum+=c
    else
        sum +=d
    end
}
puts sum

p = gets.split.map(&:to_i)
counter=0
gets.chomp.to_s.split(//).each{|x| counter+=p[x.to_i-1]}
puts counter

p = gets.split.map(&:to_i)
s = gets.chomp.to_s.split(//)

counter = 0
for i in 0..s.length-1
  case s[i]
  when "1"
    counter+=p[0]
  when "2"
    counter+=p[1]
  when "3"
    counter+=p[2]
  when "4"
    counter+=p[3]
  end
end
puts counter

arr = gets.split.map &:to_i
sum = 0
s = gets.split("").map &:to_i
4.times do |j|
  sum += s.count { |x| x == j + 1 } * arr[j]
end
puts sum

a=gets.chomp.split(" ")
b=gets.chomp
ans=0
b.each_char do |i|
ind=i.to_i-1
ans+=a[ind].to_i
end
puts "#{ans}"

as = gets.split.map(&:to_i)
ans = 0
gets.chomp.chars.map(&:to_i).each do |s|
  ans += as[s-1]
end
puts ans

a=gets.split.map{|e| e.to_i}
a.unshift(0)
s=gets.chomp
puts s.chars.inject(0){|sum,e|
	sum+a[e.to_i]
}

s = gets.split.map{ |e| e.to_i }
sum = 0
q = gets.chomp.split(//).each { |e| sum += s[e.to_i-1] }
puts sum

a=gets.split.map &:to_i
p gets.chomp.split(//).inject(0){|s,x|s+a[x.to_i-1]}

# coding: utf-8

# if __FILE__ == $0
# end

nth_calories = gets.split.map { |i| i.to_i }
notes = gets[0...-1]
total_calories = 0
notes.each_char { |c|
    total_calories += nth_calories[c.to_i - 1]
}
puts total_calories

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

print s.count(1)*a[0] + s.count(2)*a[1] + s.count(3)*a[2] + s.count(4)*a[3]

#MADE BY HAMZA HASBI

a=gets.chomp.split.map(&:to_i)
b=gets.chomp.to_s

mp=Hash.new(0)

t={'1'=>0,'2'=>1,'3'=>2,'4'=>3}

for i in '1'..'4'
  mp[i]=a[t[i]]
end

ans =0
for i in 0...b.length
  ans+=mp[b[i]]
end
puts ans

a = [nil] + gets.split.map(&:to_i)
s = gets.chomp.split("").map(&:to_i)
ans = 0
s.each do |x|
  ans += a[x]
end
p ans

a = [nil] + gets.split.map(&:to_i)
s = gets.chomp.split("").map(&:to_i)
puts s.map{|x| a[x]}.inject(:+)

a = [nil] + gets.split.map{|x| x.to_i}
puts(gets.strip.split('').map{|x| x.to_i}.inject(0){|s, x| s += a[x]})

a = gets.split(' ').map(&:to_i).unshift(0)

puts gets.chomp.chars.inject(0) { |s, x| s + a[x.to_i] }

a=gets.split(' ').map(&:to_i)
s=gets.strip
ans =0
s.each_char do |aa|
  ans+=a[aa.to_i-1]
end
puts ans

a = gets.split.map(&:to_i)
s = gets.chomp
cal = 0
s.each_char do |c|
  cal += a[c.to_i - 1]
end
puts cal


The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases.As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens — each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days?

The first input line contains space-separated integers n and c — the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly. The next n lines contain pairs of space-separated integers ai, bi (1 ≤ i ≤ n) — the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly. The input limitations for getting 30 points are:    1 ≤ n ≤ 100  1 ≤ ai ≤ 100  1 ≤ bi ≤ 100  1 ≤ c ≤ 100  The input limitations for getting 100 points are:    1 ≤ n ≤ 104  0 ≤ ai ≤ 109  1 ≤ bi ≤ 109  1 ≤ c ≤ 109  Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!

Print a single number k — the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days — he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long.

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=0
r=1
c=check(r)
while c!=1 do
  r*=2
  c=check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
	exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  if check(z)==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  if check(z)==0 then l1=z else r=z end
end

puts r-l-1

# ABBYY Cup 2.0 - Easy
# Problem E - Space Voyage
$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = 1, 10 ** 18 + 1
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = 0, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

answer = [maximum - minimum + 1, 0].max
answer = -1 if answer == 10 ** 18
puts answer

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
s = 0
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
  s+=$a[i][0]
end
if s==0 && $n==$c
  puts -1
  exit
end
if s==0 && $n!=$c
  puts 0
  exit
end
l=0
r=1
c=check(r)
while c!=1 do
  r*=2
  c=check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
	exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  if check(z)==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  if check(z)==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
s = 0
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
  s+=$a[i][0]
end
if s==0 && $n==$c
  puts -1
  exit
end
if s==0 && $n!=$c
  puts 0
  exit
end
l=0
r=1
c=check(r)
while c!=1 do
  r*=2
  c=check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
	exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  if check(z)==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  if check(z)==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>$c
end
def check2(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>=$c
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=1
r=1
c=check(r)
while !c do
  r*=2
  c=check(r)
end
l2 = l1 = l
r2 = r1 = r
while r1-l1>1 do
  m = (l1+r1)/2
  if check(m) then r1=m else l1=m end
end
while r2-l2>1 do
  m = (l2+r2)/2
  if check2(m) then r2=m else l2=m end
end
ans = l1-r2+1
puts ans

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>$c
end
def check2(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>=$c
end

def check3(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m==$c
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=1
r=1
c=check(r)
while !c do
  r*=2
  c=check(r)
end
l2 = l1 = l
r2 = r1 = r
while r1-l1>1 do
  m = (l1+r1)/2
  if check(m) then r1=m else l1=m end
end
while r2-l2>1 do
  m = (l2+r2)/2
  if check2(m) then r2=m else l2=m end
end
ans = l1-r2+1
if l1==r2 then
  c=check3(r2)
  if c then ans=1 else ans=0 end
end

puts ans

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=0
r=1
c=check(r)
while c!=1 do
  r*=2
  c=check(r)
end

m=0
puts l,r
loop do
  if r-1==l then
    puts 0
	halt
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  if check(z)==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  if check(z)==0 then l1=z else r=z end
end

puts l-r-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>$c
end
def check2(x)
  m = 0
  for i in (1..$n) do
    m+=$a[i][0]*x/$a[i][1]+1
  end
  m>=$c
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=1
r=1
c=check(r)
while !c do
  r*=2
  c=check(r)
end
l2 = l1 = l
r2 = r1 = r
while r1-l1>1 do
  m = (l1+r1)/2
  if check(m) then r1=m else l1=m end
end
while r2-l2>1 do
  m = (l2+r2)/2
  if check2(m) then r2=m else l2=m end
end
ans = l1-r2+1
if l1==r2 then
  c=check(r2)
  if c then ans=1 else ans=0 end
end

puts ans

def check(x)
  m = ($oo*x+0.000001).to_i + $n
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$oo = 0
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $oo+= a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = ($oo*x+0.00000001).to_i + $n
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$oo = 0
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $oo+= a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.0000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    if $a[i][0]==0 then
      m+=1
    else
      m+=$a[i][0]*x/$a[i][1]+1
    end
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  $a[i] = gets.split.map{|e| e.to_i}
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(m)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(m)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.00000000000000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = ($oo*x+0.0000000000001).to_i + $n
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$oo = 0
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $oo+= a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = ($oo*x).to_i + $n
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$oo = 0.to_r
for i in (1..$n) do
  a = gets.split.map{|e| e.to_r}
  $oo+= a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.000000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.0000000000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

def check(x)
  m = 0
  for i in (1..$n) do
    m+=($a[i]*x+1.00000000001).to_i
    if m>$c then break end
  end
  if m>$c then return 1 end
  if m==$c then return 0 end
  if m<$c then return -1 end
end

$n,$c = gets.split.map{|e| e.to_i}
$a = []
for i in (1..$n) do
  a = gets.split.map{|e| e.to_f}
  $a[i] = a[0]/a[1]
end
l=0
r=1
c = check(r)
while c!=1 do
  r*=2
  c = check(r)
end

m=0
loop do
  if r-1==l then
    puts 0
    exit
  end
  m = (l+r)/2
  c = check(m)
  if c==1
    r = m
  elsif c==-1
    l = m
  elsif c==0
    break
  end
end

l1 = r1 = m
while r1-l>1 do
  z = (l+r1)/2
  c = check(z)
  if c==0 then r1=z else l=z end
end

while r-l1>1 do
  z = (l1+r)/2
  c = check(z)
  if c==0 then l1=z else r=z end
end

puts r-l-1

$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = 0, 10 ** 18
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = 0, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

puts [maximum - minimum + 1, 0].max

$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = 1, 10 ** 18
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = 0, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

puts [maximum - minimum + 1, 0].max

$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = 1, 10 ** 18
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = 0, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

answer = [maximum - minimum + 1, 0].max
answer = -1 if answer == 10 ** 18
puts answer

$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = -1, 10 ** 18
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = -1, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

puts [maximum - minimum + 1, 0].max

$n, c = gets.split.map(&:to_i)
$a, $b = [], []
$n.times do
    a_i, b_i = gets.split.map(&:to_i)
    $a << a_i
    $b << b_i
end

def get_value(x)
    ret = $n
    $n.times do |i|
        ret += $a[i] * x / $b[i]
    end
    ret
end

low, high = 0, 10 ** 18
while low < high
    middle = low + high >> 1
    if get_value(middle) >= c
        high = middle
    else
        low = middle + 1
    end
end
minimum = high

low, high = -1, 10 ** 18
while low < high
    middle = low + high + 1 >> 1
    if get_value(middle) <= c
        low = middle
    else
        high = middle - 1
    end
end
maximum = low

puts [maximum - minimum + 1, 0].max


Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:  either the boy in the dancing pair must dance for the first time (so, he didn't dance with anyone before);  or the girl in the dancing pair must dance for the first time. Help Fox Ciel to make a schedule that they can dance as many songs as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of boys and girls in the dancing room.

In the first line print k — the number of songs during which they can dance. Then in the following k lines, print the indexes of boys and girls dancing during songs chronologically. You can assume that the boys are indexed from 1 to n, and the girls are indexed from 1 to m.

NoteIn test case 1, there are 2 boys and 1 girl. We can have 2 dances: the 1st boy and 1st girl (during the first song), the 2nd boy and 1st girl (during the second song).And in test case 2, we have 2 boys with 2 girls, the answer is 3.

a, b = gets.split.map(&:to_i)
p a + b - 1
puts "1 1"
2.upto(a) do |i|
  puts "#{i} 1"
end
2.upto(b) do |i|
  puts "1 #{i}"
end

#!/usr/bin/env ruby
n, m = gets.split(' ').map(&:to_i)
puts n + m - 1
n.times do |i|
  puts "#{i + 1} 1"
end
(m - 1).times do |i|
  puts "1 #{i + 2}"
end

require "Matrix"

h=Matrix
n, m = gets.split.map{|i| i.to_i}
puts(n+m-1)
for i in 1..m
  puts("1 #{i}")
end
for i in 2..n
  puts("#{i} 1")
end

n = gets(" ")
m = gets
n = n.to_i
m = m.to_i
puts m + n - 1
m.times { |x| print "1 #{x+1}\n"}
(n-1).times { |x|
	print "#{x+2} #{m > 1 ? 2 : 1}\n"}

def run
  n, m = $stdin.readline.split.map(&:to_i)

  puts n + m - 1

  n.times do |i|
    puts "#{i + 1} 1"
  end

  if n == 1
    (m - 1).times do |i|
      puts "1 #{i + 2}"
    end
  elsif m > 1
    (m - 1).times do |i|
      puts "2 #{i + 2}"
    end
  end
end

run if $0 == __FILE__

def run
  n, m = $stdin.readline.split.map(&:to_i)

  puts n + m - 1

  n.times do |i|
    puts "#{i + 1} 1"
  end

  (m - 1).times do |i|
    if n == 1
      puts "1 #{i + 2}"
    else
      puts "2 #{i + 2}"
    end
  end
end

run if $0 == __FILE__

class A
  def initialize
    n, m = gets.chomp.split(' ').map(&:to_i)

    res = n+m-1
    ans = []

    1.upto(m) do |index|
      ans << [1,index]
    end

    2.upto(n) do |index|
      ans << [index, m]
    end

    puts ans.size
    ans.each do |a|
      puts a.join(' ')
    end
  end

end

a = A.new

a=gets.chomp.split(" ")
ans=-1
a=a.each do |i|
a[a.index(i)]=i.to_i
ans+=i.to_i
end
t=0
if a[0]>a[1]
t=1
end
a.sort!
a.reverse!
puts "#{ans}"
n=0
m=1
trig1=1
trig2=-1
loop do
if n<a[0] && trig1>0
n+=1
end
if m<a[1] && trig2>0
m+=1
end
trig1=trig1*(-1)
trig2=trig1*(-1)
if t== 1
puts "#{n} #{m}"
else
puts "#{m} #{n}"
end
if m==a[1]
trig1=2
end
break if n==a[0] && m==a[1]
end

n,m = gets.split.map &:to_i
cant,ln,lm = 0,1,1
nn = false
a = []
while true
    cant+=1
    a<< "#{ln} #{lm}"
    som = false
    if nn then
        if ln<n then
            ln+=1
            som=true
        elsif lm<m
            lm+=1
            som=true
        end
        nn=false
    else
        if lm<m then
            lm+=1
            som=true
        elsif ln<n then
            ln+=1
            som=true
        end
        nn=true
    end
    if !som then
        break
    end
end
puts cant
for b in a
    puts b
end

n,m=gets.split.map(&:to_i)
used1=[]
used2=[]
res=[]
1.upto(n) {|i|
    1.upto(m) {|j|
        if !used1.include?(i) or !used2.include?(j)
            res<<[i, j]
            used1<<i if !used1.include?(i)
            used2<<j if !used2.include?(j)
        end
    }
}
p res.size
res.each {|v| puts v*' '}

#!/usr/bin/ruby
include Math

n,m = gets.split.map(&:to_i)
ret = []
boys = Array.new(n,true)
girls = Array.new(m,true)
for i in 1..n
  for j in 1..m
    if boys[i-1] || girls[j-1]
      boys[i-1] = false
      girls[j-1] = false
      ret << [i,j].join(" ")
    end
  end
end
puts ret.size
puts ret.join "\n"

class Pair
  attr_accessor :first, :second
  def initialize(first,second)
    @first = first
    @second = second
  end
  def to_s()
    "#{@first} #{@second}"
  end
end

n,m = gets.split.map &:to_i
cont=0
may = [n,m].max
men = [n,m].min
vec = Array.new
for i in 1...men
  for j in i..i+1
    cont+=1
    vec<<Pair.new(i,j)
  end
end

for i in men..may
  (men == n)? vec<<Pair.new(men,i) : vec<<Pair.new(i,men)
  cont+=1
end

puts cont

for elem in vec
  puts elem.to_s
end

n,m = STDIN.readline.split.map(&:to_i)
puts n+m-1
(1..n).each{|x|
  puts "#{x} 1"
}
(2..m).each{|x|
  puts "1 #{x}"
}

#!/usr/bin/ruby
guys, girls = gets.chomp.split(" ").map{ |x| x.to_i}

puts girls + guys - 1
lesser = [girls, guys].min
greater = [girls, guys].max

girls_first = lesser == girls

# all but one girl
min_greater = 1
for i in 1..lesser -1 do
    puts "1 " + i.to_s if girls_first
    puts i.to_s + " 1" if !girls_first

end

for i in min_greater..greater do
    puts i.to_s + " " + lesser.to_s if girls_first
    puts lesser.to_s + " " + i.to_s if !girls_first
end

n, m = gets.strip.split(" ").collect{|v| v.to_i}
puts (m + n - 1)
(1..n).each{|i| puts [i, 1].join(" ")}
(2..m).each{|j| puts [1, j].join(" ")}

a, b = gets.split.map(&:to_i)
p a + b - 1
puts"1 1"
2.upto(a) do |i|
	puts "#{i} 1"
end
2.upto(b) do |i|
	puts "1 #{i}"
end

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

puts n + m - 1

m.times { |i| puts "1 #{i+1}" }
(n-1).times { |i| puts "#{i+2} 1" }

m, n = gets.chomp.split.map { |x| x.to_i }
puts n + m - 1
for i in 1..n
  puts "1 #{i}"
end
for i in 2..m
  puts "#{i} 1"
end

boys, girls = gets.chomp.split.map(&:to_i)
puts boys + girls - 1
(1..girls).each { |e| puts "1 #{e}" }
(2..boys).each { |e| puts "#{e} 1" }

n, m = gets.split.map(&:to_i)
puts n + m - 1
puts [*1..n].map{|i| i.to_s+" 1"}
puts [*2..m].map{|i| "1 "+i.to_s}

n = gets(" ")
m = gets
n = n.to_i
m = m.to_i
puts m + n - 1
m.times { |x| print "1 #{x+1}\n"}
(n-1).times { |x| print "#{x+2} 2\n"}

n = gets(" ")
m = gets
n = n.to_i
m = m.to_i
puts m + n - 1
if m < n
	m, n = n, m
end
m.times { |x| print "1 #{x+1}\n"}
(n-1).times { |x| print "#{x+2} 2\n"}

def run
  n, m = $stdin.readline.split.map(&:to_i)

  puts n + m - 1

  n.times do |i|
    puts "#{i + 1} 1"
  end

  if m > 1
    (m - 1).times do |i|
      puts "2 #{i + 2}"
    end
  end
end

run if $0 == __FILE__

a=gets.chomp.split(" ")
ans=-1
a=a.each do |i|
a[a.index(i)]=i.to_i
ans+=i.to_i
end
a.sort!
a.reverse!
puts "#{ans}"
#puts "1 1"
n=0
m=1
trig1=1
trig2=-1
loop do
if n<a[0] && trig1>0
n+=1
end
if m<a[1] && trig2>0
m+=1
end
trig1=trig1*(-1)
trig2=trig1*(-1)
puts "#{n} #{m}"
if m==a[1]
trig1=2
end
break if n==a[0] && m==a[1]
end

#!/usr/bin/ruby
include Math

n,m = gets.split.map(&:to_i)
ret = []
for i in 1..n
  for j in 1..m
    ret << [i,j].join(" ")
  end
end
puts ret.size
puts ret.join "\n"


A row of $$$n$$$ cells is given, all initially white. Using a stamp, you can stamp any two neighboring cells such that one becomes red and the other becomes blue. A stamp can be rotated, i.e. it can be used in both ways: as $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}$$$ and as $$$\color{red}{\texttt{R}}\color{blue}{\texttt{B}}$$$.During use, the stamp must completely fit on the given $$$n$$$ cells (it cannot be partially outside the cells). The stamp can be applied multiple times to the same cell. Each usage of the stamp recolors both cells that are under the stamp.For example, one possible sequence of stamps to make the picture $$$\color{blue}{\texttt{B}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\color{blue}{\texttt{B}}\texttt{W}$$$ could be $$$\texttt{WWWWW} \to \texttt{WW}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\texttt{W} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{red}{\texttt{R}}\color{blue}{\texttt{B}}\texttt{W} \to \color{blue}{\texttt{B}}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}\texttt{W}$$$. Here $$$\texttt{W}$$$, $$$\color{red}{\texttt{R}}$$$, and $$$\color{blue}{\texttt{B}}$$$ represent a white, red, or blue cell, respectively, and the cells that the stamp is used on are marked with an underline.Given a final picture, is it possible to make it using the stamp zero or more times?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the picture. The second line of each test case contains a string $$$s$$$ — the picture you need to make. It is guaranteed that the length of $$$s$$$ is $$$n$$$ and that $$$s$$$ only consists of the characters $$$\texttt{W}$$$, $$$\texttt{R}$$$, and $$$\texttt{B}$$$, representing a white, red, or blue cell, respectively. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. As an answer, output "YES" if it possible to make the picture using the stamp zero or more times, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

12
5
BRBBW
1
B
2
WB
2
RW
3
BRB
3
RBB
7
WWWWWWW
9
RBWBWRRBW
10
BRBRBRBRRB
12
BBBRWWRRRWBR
10
BRBRBRBRBW
5
RBWBW

YES
NO
NO
NO
YES
YES
YES
NO
YES
NO
YES
NO

NoteThe first test case is explained in the statement.For the second, third, and fourth test cases, it is not possible to stamp a single cell, so the answer is "NO".For the fifth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{blue}{\texttt{B}}\color{red}{\texttt{R}}}}\color{blue}{\texttt{B}}$$$.For the sixth test case, you can use the stamp as follows: $$$\texttt{WWW} \to \texttt{W}\color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}} \to \color{brown}{\underline{\color{red}{\texttt{R}}\color{blue}{\texttt{B}}}}\color{blue}{\texttt{B}}$$$.For the seventh test case, you don't need to use the stamp at all.

gets.to_i.times do
  gets
  s = gets.chomp
  ok = s.split("W").reject(&:empty?).all? { |s| s.include?("R") && s.include?("B") }
  puts ok ? "YES" : "NO"
end

def isvalid(s)
  n = s.size
  return true if n.zero?
  return false if n == 1

  for i in 0..n - 2
    return true unless s[i] == s[i + 1]
  end
  false
end

def solve
  gets
  f = true
  gets.chomp.split('W').each do |s|
    f = false unless isvalid(s)
  end
  puts f ? :YES : :NO
end

gets.to_i.times do
  solve
end


A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string $$$s$$$ determine if it is square.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) —the number of test cases. This is followed by $$$t$$$ lines, each containing a description of one test case. The given strings consist only of lowercase Latin letters and have lengths between $$$1$$$ and $$$100$$$ inclusive.

For each test case, output on a separate line:   YES if the string in the corresponding test case is square,  NO otherwise.  You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

10
a
aa
aaa
aaaa
abab
abcabc
abacaba
xxyy
xyyx
xyxy

t = gets.chomp.to_i
t.times do |n|
    lin = gets.chomp
    ln = lin.size
    lin1 = ""
    lin2 = ""
    if ln%2 == 0
        ln.times do |i|
            if i< (ln/2)
                lin1 += lin[i]
            else
                lin2 += lin[i]
            end
        end
    end
    if lin1!= "" && lin1 == lin2
        puts "YES"
    else
        puts "NO"
    end

end

  n = gets.to_i
  n.times do
    str = gets.to_s.strip
    len = str.length
    ans = if len.even?
            half = len / 2
            str[0...half] == str[half..] ? 'YES' : 'NO'
          else
            'NO'
          end
    puts ans
  end

n = gets.chomp.to_i
n.times do
    w = gets.chomp
    puts (w[0...w.length/2] == w[w.length/2..] ? "YES" : "NO")
end

n = gets.to_i
a = []

def find_ans(w)
  if w.length.odd?
    'NO'
  else
    if w[0..w.length/2 - 1] == w[w.length/2..w.length]
      'YES'
    else
      'NO'
    end
  end
end

(0..n-1).each do |x|
  w = gets.chomp
	a.append(find_ans(w))
end

a.each do |x|
 puts x
end

t = gets.to_i
inputs = []
(0...t).each do |i|
  str = gets.chomp
  inputs << str
end

inputs.each do |str|
  len = str.length
  if len == 1
    puts "NO"
    next
  end
  m = len/2
  substr1 = str[0..m-1]
  substr2 = str[m..len]
  if substr1 == substr2
    puts "YES"
  else
    puts "NO"
  end
end

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

inputs.each do |input|
  if input.length % 2 != 0
    puts "NO"
    next
  end

  if input[0..input.length/2 - 1] == input[input.length/2..input.length]
    puts "YES"
  else
    puts "NO"
  end
end

t = gets.chomp.to_i
t.times do |n|
    lin = gets.chomp
    ln = lin.size
    lin1 = ""
    lin2 = ""
    if ln%2 == 0
        ln.times do |i|
            if i< (ln/2)
                lin1 += lin[i]
            else
                lin2 += lin[i]
            end
        end
    end
    if lin1!= "" && lin1 == lin2
        p "YES"
    else
        p "NO"
    end

end

t = gets.to_i
t.times do |n|
    lin = gets
    ln = lin.length
    lin1 = ""
    lin2 = ""
    if ln%2 == 0
        ln.times do |i|
            if i< (ln/2)
                lin1 += lin[i]
            else
                lin2 += lin[i]
            end
        end
    end
    if lin1!= "" && lin1 == lin2
        p "YES"
    else
        p "NO"
    end

end

t = gets.to_i
t.times do |n|
    lin = gets
    ln = lin.size
    lin1 = ""
    lin2 = ""
    if ln%2 == 0
        ln.times do |i|
            if i< (ln/2)
                lin1 += lin[i]
            else
                lin2 += lin[i]
            end
        end
    end
    if lin1!= "" && lin1 == lin2
        p "YES"
    else
        p "NO"
    end

end

n = gets.to_i
n.times do
  str = gets.to_s
  len = str.length
  ans = if len.even?
          half = len / 2
          str[0...half] == str[half..] ? 'YES' : 'NO'
        else
          'NO'
        end
  puts ans
end

s = gets.chomp
puts (s[0...s.length/2] == s[s.length/2..] ? "YES" : "NO")

n = gets.to_i
a = []

def find_ans(w)
  if w.length.odd?
    'NO'
  else
    if w[0..w.length/2 - 1] == w[w.length/2..w.length]
      'YES'
    else
      'NO'
    end
  end
end

(0..n-1).each do |x|
  w = gets.chomp
	a.append(find_ans(w))
end

a.each do |x|
 p x
end


After lessons Nastya decided to read a book. The book contains $$$n$$$ chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number $$$k$$$ as the first page which was not read (i.e. she read all pages from the $$$1$$$-st to the $$$(k-1)$$$-th).The next day Nastya's friend Igor came and asked her, how many chapters remain to be read by Nastya? Nastya is too busy now, so she asks you to compute the number of chapters she has not completely read yet (i.e. the number of chapters she has not started to read or has finished reading somewhere in the middle).

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of chapters in the book. There are $$$n$$$ lines then. The $$$i$$$-th of these lines contains two integers $$$l_i$$$, $$$r_i$$$ separated by space ($$$l_1 = 1$$$, $$$l_i \leq r_i$$$) — numbers of the first and the last pages of the $$$i$$$-th chapter. It's guaranteed that $$$l_{i+1} = r_i + 1$$$ for all $$$1 \leq i \leq n-1$$$, and also that every chapter contains at most $$$100$$$ pages. The $$$(n+2)$$$-th line contains a single integer $$$k$$$ ($$$1 \leq k \leq r_n$$$) — the index of the marked page.

Print a single integer — the number of chapters which has not been completely read so far.

NoteIn the first example the book contains $$$11$$$ pages and $$$3$$$ chapters — $$$[1;3]$$$, $$$[4;7]$$$ and $$$[8;11]$$$. Nastya marked the $$$2$$$-nd page, so she finished in the middle of the $$$1$$$-st chapter. So, all chapters has not been read so far, so the answer is $$$3$$$.The book in the second example contains $$$12$$$ pages and $$$3$$$ chapters too, but Nastya finished reading in the middle of the $$$2$$$-nd chapter, so that the answer is $$$2$$$.

n = gets.to_i
l = Array.new(n)
r = Array.new(n)
n.times do |i|
  l[i], r[i] = gets.split.map(&:to_i)
end
k = gets.to_i
puts r.count { |rr| rr >= k }

n = gets.to_i
ch = []
(1..n).each do |i|
    ch << gets.split(" ").map(&:to_i)
end
k = gets.to_i

res = 0
(0..n-1).each do |i|
    if k > ch[i][1]
        res += 1
    end
end

puts n-res

n = gets.to_i
l, r = [], []
n.times do
    li, ri = gets.split.map(&:to_i)
    l << li
    r << ri
end
k = gets.to_i
i = 0
loop do
    break if k <= r[i]
    i += 1
end
puts n - i


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

s=gets.chomp
n=gets.to_i
puts s.size<n ? :impossible : [0,n-s.chars.uniq.size].max

s=gets.chomp
k=gets.to_i
if k>s.size
	puts "impossible"
else
	n=s.chars.uniq.size
	puts [0, k-n].max
end

s=gets.chomp.chars
k=gets.to_i
puts k > s.size ? :impossible : [0, k - s.uniq.size].max

s, k = gets.chomp.chars, gets.to_i
puts k > s.size ? :impossible : [0, k - s.uniq.size].max

s=gets.chomp.chars
k=gets.to_i
puts k > s.size ? :impossible : [k - s.uniq.size].max

s, cnt, k = gets.chomp, Array.new(26, 0), gets.to_i
s.chars {|c| cnt[c.ord - 97] += 1}
cnt.reject! {|c| c.zero?}
puts k > s.length ? :impossible : k - cnt.length

cnt = Array.new(26, 0)
gets.chomp.chars {|c|
  cnt[c.ord - 97] += 1
}
cnt.reject! {|c| c.zero?}
k = gets.to_i - cnt.length
puts k > cnt.reduce(:+) ? :impossible : k

cnt = Array.new(26, 0)
gets.chomp.chars {|c|
  cnt[c.ord - 97] += 1
}
cnt.reject! {|c| c.zero?}
k = gets.to_i
puts k > cnt.reduce(:+) ? :impossible : k - cnt.length


Let's call a binary string $$$T$$$ of length $$$m$$$ indexed from $$$1$$$ to $$$m$$$ paranoid if we can obtain a string of length $$$1$$$ by performing the following two kinds of operations $$$m-1$$$ times in any order : Select any substring of $$$T$$$ that is equal to 01, and then replace it with 1. Select any substring of $$$T$$$ that is equal to 10, and then replace it with 0.For example, if $$$T = $$$ 001, we can select the substring $$$[T_2T_3]$$$ and perform the first operation. So we obtain $$$T = $$$ 01.You are given a binary string $$$S$$$ of length $$$n$$$ indexed from $$$1$$$ to $$$n$$$. Find the number of pairs of integers $$$(l, r)$$$ $$$1 \le l \le r \le n$$$ such that $$$S[l \ldots r]$$$ (the substring of $$$S$$$ from $$$l$$$ to $$$r$$$) is a paranoid string.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the size of $$$S$$$. The second line of each test case contains a binary string $$$S$$$ of $$$n$$$ characters $$$S_1S_2 \ldots S_n$$$. ($$$S_i = $$$ 0 or $$$S_i = $$$ 1 for each $$$1 \le i \le n$$$) It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, output the number of pairs of integers $$$(l, r)$$$ $$$1 \le l \le r \le n$$$ such that $$$S[l \ldots r]$$$ (the substring of $$$S$$$ from $$$l$$$ to $$$r$$$) is a paranoid string.

NoteIn the first sample, $$$S$$$ already has length $$$1$$$ and doesn't need any operations.In the second sample, all substrings of $$$S$$$ are paranoid. For the entire string, it's enough to perform the first operation.In the third sample, all substrings of $$$S$$$ are paranoid except $$$[S_2S_3]$$$, because we can't perform any operations on it, and $$$[S_1S_2S_3]$$$ (the entire string).

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  n = gets.to_i
  s = gets.chomp.chars

  ans = n
  i = 1
  while i < n
    if s[i] != s[i-1]
      ans += i
    end
    i += 1
  end

  puts ans
end

gets.to_i.times do
  gets
  s = gets.chomp
  answer = s.size
  0.upto(s.size - 2).each do |i|
    if s[i] != s[i + 1]
      answer += i + 1
    end
  end
  p answer
end


Anton is playing a very interesting computer game, but now he is stuck at one of the levels. To pass to the next level he has to prepare n potions.Anton has a special kettle, that can prepare one potions in x seconds. Also, he knows spells of two types that can faster the process of preparing potions.  Spells of this type speed up the preparation time of one potion. There are m spells of this type, the i-th of them costs bi manapoints and changes the preparation time of each potion to ai instead of x.  Spells of this type immediately prepare some number of potions. There are k such spells, the i-th of them costs di manapoints and instantly create ci potions. Anton can use no more than one spell of the first type and no more than one spell of the second type, and the total number of manapoints spent should not exceed s. Consider that all spells are used instantly and right before Anton starts to prepare potions.Anton wants to get to the next level as fast as possible, so he is interested in the minimum number of time he needs to spent in order to prepare at least n potions.

The first line of the input contains three integers n, m, k (1 ≤ n ≤ 2·109, 1 ≤ m, k ≤ 2·105) — the number of potions, Anton has to make, the number of spells of the first type and the number of spells of the second type. The second line of the input contains two integers x and s (2 ≤ x ≤ 2·109, 1 ≤ s ≤ 2·109) — the initial number of seconds required to prepare one potion and the number of manapoints Anton can use. The third line contains m integers ai (1 ≤ ai < x) — the number of seconds it will take to prepare one potion if the i-th spell of the first type is used. The fourth line contains m integers bi (1 ≤ bi ≤ 2·109) — the number of manapoints to use the i-th spell of the first type. There are k integers ci (1 ≤ ci ≤ n) in the fifth line — the number of potions that will be immediately created if the i-th spell of the second type is used. It's guaranteed that ci are not decreasing, i.e. ci ≤ cj if i < j. The sixth line contains k integers di (1 ≤ di ≤ 2·109) — the number of manapoints required to use the i-th spell of the second type. It's guaranteed that di are not decreasing, i.e. di ≤ dj if i < j.

Print one integer — the minimum time one has to spent in order to prepare n potions.

NoteIn the first sample, the optimum answer is to use the second spell of the first type that costs 10 manapoints. Thus, the preparation time of each potion changes to 4 seconds. Also, Anton should use the second spell of the second type to instantly prepare 15 potions spending 80 manapoints. The total number of manapoints used is 10 + 80 = 90, and the preparation time is 4·5 = 20 seconds (15 potions were prepared instantly, and the remaining 5 will take 4 seconds each).In the second sample, Anton can't use any of the spells, so he just prepares 20 potions, spending 10 seconds on each of them and the answer is 20·10 = 200.

n, m, k = gets.strip.split.map(&:to_i)
x, s = gets.strip.split.map(&:to_i)
ai = gets.strip.split.map(&:to_i)
bi = gets.strip.split.map(&:to_i)
ci = gets.strip.split.map(&:to_i)
di = gets.strip.split.map(&:to_i)

type2 = []
(k-1).downto(0).each do |i|
  type2 << [di[i], ci[i]]
end

ans = n*x

sp2 = type2.bsearch{|i| i[0]<=s}
ans = [ans, [n - sp2[1], 0].max * x].min if sp2

0.upto(m-1).each do |i|
  if s >= bi[i]
    rem = s - bi[i]
    sp2 = type2.bsearch{|j| j[0]<=rem}
    if sp2
      ans = [ans, [n - sp2[1], 0].max * ai[i]].min
    else
      ans = [ans, n * ai[i]].min
    end
  end
end

puts ans

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort{|u, v|
    if u[1] != v[1]
        v[1] <=> u[1]
    else
        v[0] <=> u[0]
    end
}

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    res = [res, (n - cj) * ai].min
end
cd.reverse.each do |cj, dj|
    break if dj > s
    res = [res, (n - cj) * x].min
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort{|u, v|
    if u[1] != v[1]
        v[1] <=> u[1]
    else
        v[0] <=> u[0]
    end
}

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    if cj <= n
        res = [res, (n - cj) * ai].min
    else
        res = [res, ai].min
    end
end
cd.reverse.each do |cj, dj|
    break if dj > s
    if cj <= n
        res = [res, (n - cj) * x].min
    else
        res = [res, x].min
    end
end

puts res

#!/bin/ruby

# n m k       n = total potions to produce, m = number of a/b, k = number of c/d
# x s         initial rate, manapoints available
# a1 a2 a3... (new rate, # of seconds per potion)
# b1 b2 b3... (cost  to speed up rate)
# c1 c2 c3... c1 <= c2, number of instant potions
# d1 d2 d3... d1 <= d2, cost of instant potions

# min total time spent to produce the potions
# for picked zero or one spell of each type

def find_next_smallest(input, target)
  left = 0
  right = input.size - 1
  while right != left
    midpoint = (right + left) / 2
    if right - left == 1
      # adjacent
      if input[right] > target
        return left
      else
        return right
      end
    elsif input[midpoint] > target
      right = midpoint - 1
    else
      left = midpoint
    end
  end

  return left
end

# read input
n, m, k = gets.strip.split(' ').map{ |x| x.to_i }
x, s = gets.strip.split(' ').map{ |x| x.to_i }
a = gets.strip.split(' ').map{ |x| x.to_i }
b = gets.strip.split(' ').map{ |x| x.to_i }
c = gets.strip.split(' ').map{ |x| x.to_i }
d = gets.strip.split(' ').map{ |x| x.to_i }

# base case, no type 1 spell
j = find_next_smallest(d, s)
rem_potion = n
rem_potion = n - c[j] if d[j] <= s
best_time = rem_potion * x

# consider each type 1 spell
0.upto(m-1) do |i|
  next if s < b[i]

  # find largest type 2 spell that can fit in remainder of s
  target = s - b[i]
  j = find_next_smallest(d, target)

  # compute timing
  rem_potion = n
  rem_potion = n - c[j] if d[j] <= target
  time = rem_potion * a[i]
  best_time = time if time < best_time
end

puts best_time

r = proc {gets.split.map(&:to_i)}
n = r.call[0]
x, s = r.call
a = r.call
b = r.call
q1 = a.zip(b)
c = r.call
d = r.call
q2 = c.zip(d)
q2.reverse!
c = q2.bsearch{|c, d| s>=d} || [0,0]
sol = (n-c[0]) * x
(q1.select{|a,b| b<=s}).each do |a,b|
  c = q2.bsearch{|c, d| (s-b)>=d} || [0,0]
  sol = [sol, (n-c[0])*a].min
end
puts sol

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|_, di| di}

res = n * x

k.times do |i|
    di = cd[i][1]
    break if di > s
    ci = cd[i][0]
    rm = n
    if ci >= n
        rm = 1
        res = [res, x].min
    else
        rm = n - ci
        res = [res, rm * x].min
    end
    m.times do |j|
        break if ab[j][1] + di > s
        res = [res, rm * ab[j][1]].min
    end
end
m.times do |j|
    break if ab[j][1] > s
    res = [res, n * ab[j][0]].min
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|_, di| -di}

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    res = [res, (n - cj) * ai].min
end
cd.reverse.each do |cj, dj|
    break if dj > s
    res = [res, (n - cj) * x].min
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|ci, di| [-di, -ci] }

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    if cj < n
        res = [res, (n - cj) * ai].min
    else
        res = [res, ai].min
    end
end
cd.reverse.each do |cj, dj|
    break if dj > s
    if cj < n
        res = [res, (n - cj) * x].min
    else
        res = [res, x].min
    end
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b) #.sort_by{|_, bi| bi}
cd = c.zip(d).reverse #.sort_by{|ci, di| [-di, -ci] }

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    if cj <= n
        res = [res, (n - cj) * ai].min
    else
        res = [res, ai].min
    end
end
cd.reverse.each do |cj, dj|
    break if dj > s
    if cj <= n
        res = [res, (n - cj) * x].min
    else
        res = [res, x].min
    end
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}.reverse
cd = c.zip(d).sort_by{|_, di| di}

res = n * x

k.times do |i|
    di = cd[i][1]
    break if di > s
    ci = cd[i][0]
    rm = n
    if ci >= n
        rm = 1
        res = [res, x].min
    else
        rm = n - ci
        res = [res, rm * x].min
    end
    ai, bi = ab.bsearch{|_, bi| bi + di <= s}
    res = [res, rm * ai].min
end
m.times do |j|
    break if ab[j][1] > s
    res = [res, n * ab[j][0]].min
end

puts res

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|_, di| di}

res = n * x

k.times do |i|
    di = cd[i][1]
    break if di > s
    ci = cd[i][0]
    rm = n
    if ci >= n
        rm = 1
        res = [res, x].min
        next
    else
        rm = n - ci
        res = [res, rm * x].min
    end
    m.times do |j|
        break if ab[j][1] + di > s
        res = [res, rm * ab[j][1]].min
    end
end
m.times do |j|
    break if ab[j][1] > s
    res = [res, n * ab[j][0]].min
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|_, di| -di}

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    res = [res, (n - cj) * ai].min
end
k.times do |j|
    break if cd[j][1] > s
    res = [res, (n - cd[j][0]) * x].min
end

puts res

# Codeforces My Practice
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

ab = a.zip(b).sort_by{|_, bi| bi}
cd = c.zip(d).sort_by{|_, di| -di}

res = n * x

m.times do |i|
    bi = ab[i][1]
    break if bi > s
    ai = ab[i][0]
    res = [res, n * ai].min
    cj, _ = cd.bsearch{|_, dj| bi + dj <= s}
    next if cj.nil?
    if cj < n
        res = [res, (n - cj) * ai].min
    else
        res = [res, ai].min
    end
end
cd.reverse.each do |cj, dj|
    break if dj > s
    res = [res, (n - cj) * x].min
end

puts res

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

res = n * x

k.times do |i|
    di = d[i]
    break if di > s
    ci = c[i]
    rm = n
    if ci >= n
        rm = 1
        res = [res, x].min
    else
        rm = n - ci
        res = [res, rm * x].min
    end
    m.times do |j|
        break if b[j] + di > s
        res = [res, rm * a[j]].min
    end
end
m.times do |j|
    break if b[j] > s
    res = [res, n * a[j]].min
end

puts res

# Try Codeforces
# author: Leonardone @ NEETSDKASU
############################################################
def gs() gets.strip end
def gi() gets.to_i end
def gss() gs.split end
def gis() gss.map(&:to_i) end
def nmapf(n,f) n.times.map{ __send__ f } end
def ngs(n) nmapf n,:gs end
def ngi(n) nmapf n,:gi end
def ngss(n) nmapf n,:gss end
def ngis(n) nmapf n,:gis end
def arr2d(h,w,v=0) h.times.map{[v] * w} end
def for2p(hr,wr,&pr) hr.each{|i|wr.each{|j| yield(i,j)}} end
def nsum(n) n * (n + 1) / 2 end
def vcount(d,r=Hash.new(0)) d.inject(r){|m,e| m[e]+=1;m} end
############################################################

n, m, k = gis
x, s = gis
a = gis # speed
b = gis # cost
c = gis # create
d = gis # cost

res = n * x

k.times do |i|
    di = d[i]
    next if di > s
    ci = c[i]
    rm = n
    if ci >= n
        rm = 1
        res = [res, x].min
    else
        rm = n - ci
        res = [res, rm * x].min
    end
end
m.times do |j|
    next if b[j] > s
    res = [res, n * a[j]].min
end

puts res

r = proc {gets.split.map(&:to_i)}
n, m, k = r.call
x, s = r.call
a = r.call
b = r.call
q1 = a.zip(b)
c = r.call
d = r.call
q2 = c.zip(d)
q2.reverse!
sol = x * n
(q1.select{|a,b| b<=s}).each do |a,b|
  c = q2.bsearch{|c, d| (s-b) > d} || [0,0]
  sol = [sol, (n-c[0])*a].min
end
puts sol

r = proc {gets.split.map(&:to_i)}
n, m, k = r.call
x, s = r.call
a = r.call
b = r.call
q1 = a.zip(b)
c = r.call
d = r.call
q2 = c.zip(d)
sol = x * n
(q1.select{|a,b| b<=s}).each do |a,b|
  c = q2.bsearch{|c, d| [(s-b)-d, 0].min} || [0,0]
  sol = [sol, (n-c[0])*a].min
end
puts sol

r = proc {gets.split.map(&:to_i)}
n = r.call[0]
x, s = r.call
a = r.call
b = r.call
q1 = a.zip(b)
c = r.call
d = r.call
q2 = c.zip(d)
q2.reverse!
c = q2.bsearch{|c, d| s>d} || [0,0]
sol = (n-c[0]) * x
(q1.select{|a,b| b<=s}).each do |a,b|
  c = q2.bsearch{|c, d| (s-b)>d} || [0,0]
  sol = [sol, (n-c[0])*a].min
end
puts sol


Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measurements. We assume that the marks are numbered from 1 to n in the order they appear from the beginning of the ruler to its end. The first point coincides with the beginning of the ruler and represents the origin. The last mark coincides with the end of the ruler, at distance l from the origin. This ruler can be repesented by an increasing sequence a1, a2, ..., an, where ai denotes the distance of the i-th mark from the origin (a1 = 0, an = l).Valery believes that with a ruler he can measure the distance of d centimeters, if there is a pair of integers i and j (1 ≤ i ≤ j ≤ n), such that the distance between the i-th and the j-th mark is exactly equal to d (in other words, aj - ai = d). Under the rules, the girls should be able to jump at least x centimeters, and the boys should be able to jump at least y (x < y) centimeters. To test the children's abilities, Valery needs a ruler to measure each of the distances x and y. Your task is to determine what is the minimum number of additional marks you need to add on the ruler so that they can be used to measure the distances x and y. Valery can add the marks at any integer non-negative distance from the origin not exceeding the length of the ruler.

The first line contains four positive space-separated integers n, l, x, y (2 ≤ n ≤ 105, 2 ≤ l ≤ 109, 1 ≤ x < y ≤ l) — the number of marks, the length of the ruler and the jump norms for girls and boys, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (0 = a1 < a2 < ... < an = l), where ai shows the distance from the i-th mark to the origin.

In the first line print a single non-negative integer v — the minimum number of marks that you need to add on the ruler. In the second line print v space-separated integers p1, p2, ..., pv (0 ≤ pi ≤ l). Number pi means that the i-th mark should be at the distance of pi centimeters from the origin. Print the marks in any order. If there are multiple solutions, print any of them.

NoteIn the first sample it is impossible to initially measure the distance of 230 centimeters. For that it is enough to add a 20 centimeter mark or a 230 centimeter mark.In the second sample you already can use the ruler to measure the distances of 185 and 230 centimeters, so you don't have to add new marks.In the third sample the ruler only contains the initial and the final marks. We will need to add two marks to be able to test the children's skills.

n, l, x, y = STDIN.readline.split.map {|s| s.to_i }
distances = STDIN.readline.split.map {|s| s.to_i }
distance_hash = {}
distances.each {|d| distance_hash[d] = true }
found_x, found_y, xy = false, false, nil
distances.each do |d|
	found_x = true if distance_hash.has_key?(d+x)
	found_y = true if distance_hash.has_key?(d+y)
	if xy == nil
		xy = d+x if distance_hash.has_key?(d+x+y)
		if distance_hash.has_key?(d+x-y)
			if d+x <= l
				xy = d+x
			elsif d-y >= 0
				xy = d-y
			end
		end
		if distance_hash.has_key?(d+y-x)
			if d+y <= l
				xy = d+y
			elsif d-x >= 0
				xy = d-x
			end
		end
	end
end
if found_x and found_y
	puts 0
elsif found_x
	puts "1\n%d" % y
elsif found_y
	puts "1\n%d" % x
elsif xy != nil
	puts "1\n%d" % xy
else
	puts "2\n%d %d" % [x, y]
end

n, l, x, y = STDIN.readline.split.map {|s| s.to_i }
distances = STDIN.readline.split.map {|s| s.to_i }
distance_hash = {}
distances.each {|distance| distance_hash[distance] = true }
found_x, found_y, xy = false, false, nil
distances.each do |d|
	found_x = true if distance_hash.has_key?(d+x)
	found_y = true if distance_hash.has_key?(d+y)
	if xy == nil
		xy = d+x if distance_hash.has_key?(d+x+y)
		if distance_hash.has_key?(d+x-y) and d+x <= l
			xy = d+x
		end
		if distance_hash.has_key?(d+y-x) and d+y <= l
			xy = d+y
		end
	end
end
if found_x and found_y
	puts 0
elsif found_x
	puts "1\n%d" % y
elsif found_y
	puts "1\n%d" % x
elsif xy != nil
	puts "1\n%d" % xy
else
	puts "2\b%d %d" % [x, y]
end

n, l, x, y = STDIN.readline.split.map {|s| s.to_i }
distances = STDIN.readline.split.map {|s| s.to_i }
distance_hash = {}
distances.each {|distance| distance_hash[distance] = true }
found_x, found_y, xy = false, false, nil
distances.each do |d|
	found_x = true if distance_hash.has_key?(d+x)
	found_y = true if distance_hash.has_key?(d+y)
	if xy == nil
		xy = d+x if distance_hash.has_key?(d+x+y)
		if distance_hash.has_key?(d+x-y)
			xy = d+x if d+x <= l
			xy = d-y if d-y >= 0
		end
		if distance_hash.has_key?(d+y-x)
			xy = d+y if d+y <= l
			xy = d-x if d-x >= 0
		end
	end
end
if found_x and found_y
	puts 0
elsif found_x
	puts "1\n%d" % y
elsif found_y
	puts "1\n%d" % x
elsif xy != nil
	puts "1\n%d" % xy
else
	puts "2\b%d %d" % [x, y]
end

n, l, x, y = STDIN.readline.split.map {|s| s.to_i }
distances = STDIN.readline.split.map {|s| s.to_i }
distance_hash = {}
distances.each {|distance| distance_hash[distance] = true }
found_x, found_y, xy = false, false, nil
distances.each do |d|
	found_x = true if distance_hash.has_key?(d+x)
	found_y = true if distance_hash.has_key?(d+y)
	xy = d+x if distance_hash.has_key?(d+x+y)
end
if found_x and found_y
	puts 0
elsif found_x
	puts "1\n%d" % y
elsif found_y
	puts "1\n%d" % x
elsif xy != nil
	puts "1\n%d" % xy
else
	puts "2\b%d %d" % [x, y]
end


You are given a string s consisting only of characters 0 and 1. A substring [l, r] of s is a string slsl + 1sl + 2... sr, and its length equals to r - l + 1. A substring is called balanced if the number of zeroes (0) equals to the number of ones in this substring.You have to determine the length of the longest balanced substring of s.

The first line contains n (1 ≤ n ≤ 100000) — the number of characters in s. The second line contains a string s consisting of exactly n characters. Only characters 0 and 1 can appear in s.

If there is no non-empty balanced substring in s, print 0. Otherwise, print the length of the longest balanced substring.

NoteIn the first example you can choose the substring [3, 6]. It is balanced, and its length is 4. Choosing the substring [2, 5] is also possible.In the second example it's impossible to find a non-empty balanced substring.

class Solver

  def self.solve(string)
    result = {}
    height = 0
    result[0] = [0]
    index = 0
    string.each_char do |char|
      index += 1
      height = height + (char == '1' ? 1 : -1)
      if result.fetch(height, nil).nil?
        result[height] = [index]
      elsif result[height].size == 1
        result[height] << index
      else
        result[height].pop
        result[height].push index
      end
      # puts "#{height}:#{index}"
      # puts result
    end
    array_result = result.values
    array_result.select! { |pair| pair.size == 2 }
    # puts array_result.inspect
    return [] if array_result.empty?
    final = array_result.max_by { |pair| pair[1] - pair.first }
    final[1] = final[1] -= 1
    final
  end

  def self.size(string)
    result = self.solve(string)
    # puts result
    return 0 if result.empty?
    result[1] - result[0] + 1
  end
end

string = ARGF.read
arr = string.split
# puts arr.inspect
puts Solver.size(arr[1])

gets
i=1
hs={}
a=0
ans=0
gets.chomp.chars.each{|e|
	a+=1 if e=="1"
	b=i-a
	if b==a
		ans=i
	else
		if hs.key?(b-a)
			ans=[ans,i-hs[b-a]].max
		end
	end
	if hs.key?(b-a)==false
		hs[b-a]=i
	end
	i+=1
}
puts ans

class Solver

  def self.solve(string)
    result = {}
    height = 0
    result[0] = [0]
    string.each_char_with_index do |char, index|
      index += 1
      height = height + (char == '1' ? 1 : -1)
      if result.fetch(height, nil).nil?
        result[height] = [index]
      elsif result[height].size == 1
        result[height] << index
      else
        result[height].pop
        result[height].push index
      end
      puts "#{height}:#{index}"
      puts result
    end
    array_result = result.values
    array_result.select! { |pair| pair.size == 2 }
    puts array_result
    return [] if array_result.empty?
    final = array_result.max_by { |pair| pair[1] - pair.first }
    final[1] = final[1] -= 1
    final
  end

  def self.size(string)
    result = self.solve(string)
    puts result
    return 0 if result.empty?
    result[1] - result[0] + 1
  end
end

class Solver

  def self.solve(string)
    result = {}
    height = 0
    result[0] = [0]
    index = 0
    string.each_char do |char|
      index += 1
      height = height + (char == '1' ? 1 : -1)
      if result.fetch(height, nil).nil?
        result[height] = [index]
      elsif result[height].size == 1
        result[height] << index
      else
        result[height].pop
        result[height].push index
      end
      # puts "#{height}:#{index}"
      # puts result
    end
    array_result = result.values
    array_result.select! { |pair| pair.size == 2 }
    # puts array_result
    return [] if array_result.empty?
    final = array_result.max_by { |pair| pair[1] - pair.first }
    final[1] = final[1] -= 1
    final
  end

  def self.size(string)
    result = self.solve(string)
    # puts result
    return 0 if result.empty?
    result[1] - result[0] + 1
  end
end

string = ARGF.read
puts Solver.size(string)

class Solver

  def self.solve(string)
    result = {}
    height = 0
    result[0] = [0]
    index = 0
    string.each_char do |char|
      index += 1
      height = height + (char == '1' ? 1 : -1)
      if result.fetch(height, nil).nil?
        result[height] = [index]
      elsif result[height].size == 1
        result[height] << index
      else
        result[height].pop
        result[height].push index
      end
      # puts "#{height}:#{index}"
      # puts result
    end
    array_result = result.values
    array_result.select! { |pair| pair.size == 2 }
    # puts array_result.inspect
    return [] if array_result.empty?
    final = array_result.max_by { |pair| pair[1] - pair.first }
    final[1] = final[1] -= 1
    final
  end

  def self.size(string)
    result = self.solve(string)
    # puts result
    return 0 if result.empty?
    result[1] - result[0] + 1
  end
end

string = ARGF.read
puts Solver.size(string.strip)


Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell $$$(x,y)$$$ of an infinite grid. According to Alice's theory, cat needs to move:   exactly $$$a$$$ steps left: from $$$(u,v)$$$ to $$$(u-1,v)$$$;  exactly $$$b$$$ steps right: from $$$(u,v)$$$ to $$$(u+1,v)$$$;  exactly $$$c$$$ steps down: from $$$(u,v)$$$ to $$$(u,v-1)$$$;  exactly $$$d$$$ steps up: from $$$(u,v)$$$ to $$$(u,v+1)$$$. Note that the moves can be performed in an arbitrary order. For example, if the cat has to move $$$1$$$ step left, $$$3$$$ steps right and $$$2$$$ steps down, then the walk right, down, left, right, right, down is valid.Alice, however, is worrying that her cat might get lost if it moves far away from her. So she hopes that her cat is always in the area $$$[x_1,x_2]\times [y_1,y_2]$$$, i.e. for every cat's position $$$(u,v)$$$ of a walk $$$x_1 \le u \le x_2$$$ and $$$y_1 \le v \le y_2$$$ holds.Also, note that the cat can visit the same cell multiple times.Can you help Alice find out if there exists a walk satisfying her wishes?Formally, the walk should contain exactly $$$a+b+c+d$$$ unit moves ($$$a$$$ to the left, $$$b$$$ to the right, $$$c$$$ to the down, $$$d$$$ to the up). Alice can do the moves in any order. Her current position $$$(u, v)$$$ should always satisfy the constraints: $$$x_1 \le u \le x_2$$$, $$$y_1 \le v \le y_2$$$. The staring point is $$$(x, y)$$$.You are required to answer $$$t$$$ test cases independently.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of testcases.  The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,b,c,d \le 10^8$$$, $$$a+b+c+d \ge 1$$$). The second line of the test case contains six integers $$$x$$$, $$$y$$$, $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$-10^8 \le x_1\le x \le x_2 \le 10^8$$$, $$$-10^8 \le y_1 \le y \le y_2 \le 10^8$$$).

For each test case, output "YES" in a separate line, if there exists a walk satisfying her wishes. Otherwise, output "NO" in a separate line.  You can print each letter in any case (upper or lower).

NoteIn the first test case, one valid exercising walk is $$$$$$(0,0)\rightarrow (-1,0) \rightarrow (-2,0)\rightarrow (-2,1) \rightarrow (-2,2)\rightarrow (-1,2)\rightarrow(0,2)\rightarrow (0,1)\rightarrow (0,0) \rightarrow (-1,0)$$$$$$

gets.to_i.times do
 left, right, down, up  = gets.split(' ').map(&:to_i)
 start_x, start_y, min_x, min_y, max_x, max_y = gets.split(' ').map(&:to_i)

 if (start_x - left + right).between?(min_x, max_x) &&
  (start_y - down + up).between?(min_y, max_y) &&
  (min_x < max_x || left + right == 0) &&
  (min_y < max_y || down + up == 0)
  puts "Yes"
 else
  puts "No"
 end
end

gets.to_i.times do
 moves = gets.split(' ').map(&:to_i)
 points = gets.split(' ').map(&:to_i)

 left = moves[0]
 right = moves[1]
 down = moves[2]
 up = moves[3]

 start_x, start_y = points[0], points[1]
 min_x, min_y = points[2], points[3]
 max_x, max_y = points[4], points[5]

 if ((start_x - left + right).between?(min_x, max_x) && (min_x < max_x || left + right == 0)) &&
  ((start_y - down + up).between?(min_y, max_y)) && (min_y < max_y || down + up == 0)

  puts "Yes"
 else
  puts "No"
 end
end

n = gets.chomp.to_i

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

  x,y,x1,y1,x2,y2 = gets.chomp.split.map(&:to_i)

  if x1 == x2 && (a > 0 || b > 0)
    puts 'No'
    next
  end

  if y1 == y2 && (c > 0 || d > 0)
    puts 'No'
    next
  end

  x += b - a
  y += d - c
  if x1 <= x && x <= x2 && y1 <= y && y <= y2
    puts 'Yes'
  else
    puts 'No'
  end
end

t = gets.to_i
t.times do
  a, b, c, d = gets.split.map(&:to_i)
  x, y, x1, y1, x2, y2 = gets.split.map(&:to_i)
  ok = true
  ok = false unless (x1..x2).include?(x - a + b)
  ok = false unless (y1..y2).include?(y - c + d)
  ok = false if (a + b > 0) && (x1 == x2)
  ok = false if (c + d > 0) && (y1 == y2)
  puts ok ? "YES" : "NO"
end

def solve(d,r)
  d > r
end

t = gets.to_i

t.times do

  l, r, d, u = gets.split.map(&:to_i)
  x, y, xl, yd, xr, yu = gets.split.map(&:to_i)

  rr = xr - x
  ll = x - xl
  uu = yu - y
  dd = y - yd

  m = rr
  m = ll if m > ll
  m = uu if m > uu
  m = dd if m > dd

  if l < r
    if solve(r-l, rr)
      puts "No"
      next
    end
  elsif l > r
    if solve(l-r, ll)
      puts "No"
      next
    end
  elsif l == r && l > 0
    if ll == 0 && rr == 0
      puts "No"
      next
    end
  end

  if d < u
    if solve(u-d,uu)
      puts "No"
      next
    end
  elsif d > u
    if solve(d-u,dd)
      puts "No"
      next
    end
  elsif d == u && d > 0
    if dd == 0 && uu == 0
      puts "No"
      next
    end
  end

  puts "Yes"
end

def solve(d,r)
  d > r
end

t = gets.to_i

t.times do

  l, r, d, u = gets.split.map(&:to_i)
  x, y, xl, yd, xr, yu = gets.split.map(&:to_i)

  rr = xr - x
  ll = x - xl
  uu = yu - y
  dd = y - yd

  m = rr
  m = ll if m > ll
  m = uu if m > uu
  m = dd if m > dd

  if l < r
    if solve(r-l, rr)
      puts "No"
      next
    end
  elsif l > r
    if solve(l-r, ll)
      puts "No"
      next
    end
  elsif l == r && l > 0
    if ll == 0 || rr == 0
      puts "No"
      next
    end
  end

  if d < u
    if solve(u-d,uu)
      puts "No"
      next
    end
  elsif d > u
    if solve(d-u,dd)
      puts "No"
      next
    end
  elsif d == u && d > 0
    if dd == 0 || uu == 0
      puts "No"
      next
    end
  end

  puts "Yes"
end


Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      a[i] = 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
        break
      end
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
p a, dot_ind, ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
      end
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  a[ind - (ind == dot_ind + 1 ? 2 : 1)] += 1
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
ind = s.each_char.with_index.find{|x, y| x.to_i >= 5}[1]
(ind - 1).downto(0) do |i|
  next if s[i] == '.'
  t -= 1
  c = s[i].to_i + 1
  s = s[0..i - 1] + c.to_s
  break if c < 5 || t <= 0
end
puts s
# dot_ind = a.find{|x, y| x == '.'}[1]
# p dot_ind

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = a[dot_ind..-1].index{|x| x >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9 && i >= 0
      if i.zero?
        a.insert(0, 0)
        ind += 1
        dot_ind += 1
      end
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5} || 0
ind -= 1
f = s.to_f
while ind >= 0 && t > 0 && f.to_s[dot_ind + ind + 1].to_i >= 5
  f = f.round(ind)
  ind -= 1
  t -= 1
end
p f

n, t = gets.split.map(&:to_i)
s = gets.chomp
dot_ind = s.index('.')
a = s.chars.map(&:to_i)
ind = s[dot_ind..-1].chars.find_index{|x| x.to_i >= 5}
if ind.nil?
  puts s
  exit
end
ind += dot_ind
while ind > dot_ind && t > 0 && a[ind] >= 5
  if ind == dot_ind + 1
    i = ind - 2
    while a[i] == 9
      a[i] = 0
      i -= 1
    end
    a[i] += 1
  else
    a[ind - 1] += 1
  end
  ind -= 1
  t -= 1
end
a[dot_ind] = ind == dot_ind ? '' : '.'
puts a[0..ind].join


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

def f(x)
  if @d[x] != nil
    return @d[x]
  end
  sum = 1
  for i in @p[x]..x - 1
    sum += f(i)
  end
  sum += 1
  @d[x] = sum
  sum
end

n = Integer gets
@p = gets.split.map { |x| (Integer x) - 1 }
@d = Array.new(n, nil)
@d[0] = 2
sum = 0
for i in 0..n - 1
  sum += f i
end
puts sum % (10 ** 9 + 7)

gets
dp,arr=[0],gets.split.map(&:to_i)
arr.each_with_index{|i,k|dp[k+1]=(dp[k]*2-dp[i-1]+2)%1000000007}
p dp[-1]

MOD = 1000000007
n = STDIN.readline.to_i
p = [0] + STDIN.readline.split.map { |x| x.to_i }

f = Array.new(n+2,0)
2.upto(n+1) do |i|
	f[i] = f[i-1]+1
	t = i-1
	while p[t] != t ;
		f[i] += f[t]-f[p[t]+1]+2
		flag = true
		t = p[t]
	end
	f[i] += 1
	f[i] %= MOD
end

print f[n+1]


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

n,*a=$<.read.split.map &:to_i
p a.max-a.min+1-n

# TEMPLATE BEGIN
def read_vector
    gets.chomp.split(/\s+/)
end
def read_vector_int
    read_vector.map(&:to_i)
end
# TEMPLATE END

gets
a = read_vector_int
puts a.max - a.min - a.size + 1

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

ans = 0
sz =ary.size

1.upto(sz-1).each do |i|
  ans += (ary[i] - ary[i-1] - 1)
end

puts ans

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

puts as[-1] - as[0] - n + 1

remain_keyborads = gets.chomp.to_i
values = gets.chomp

remain_keybord_indicies = values.split(' ')
remain_keybord_indicies.map!(&:to_i)

max = remain_keybord_indicies.max
min = remain_keybord_indicies.min

puts max - min - remain_keyborads + 1

gets
a = gets.split.map(&:to_i).sort
i = 1
ans = 0
while i < a.size
    ans += a[i] - a[i - 1] - 1
    i += 1
end
puts ans

n,*a=$<.read.split.map &:to_i
p n-a.max+a.min-1