Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n.Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers a permutation beautiful, if it has exactly k good elements. Unfortunately, he doesn’t know any beautiful permutation. Your task is to help him to find at least one of them.

The single line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ n).

In a single line print either any beautiful permutation or -1, if such permutation doesn’t exist. If there are multiple suitable permutations, you are allowed to print any of them.

NoteIn the first sample elements 4 and 3 are good because gcd(2, 4) = 2 > 1 and gcd(3, 3) = 3 > 1. Elements 2 and 1 are not good because gcd(1, 2) = 1 and gcd(4, 1) = 1. As there are exactly 2 good elements, the permutation is beautiful.The second sample has no beautiful permutations.

n,k=gets.split.map(&:to_i)
puts (n==k ? -1:(2..n).to_a.insert(n-k-1,1).join(' '))

n, k = gets.split.map{|s| s.to_i}

if n==k
	puts -1
	exit
end

seq = Array.new(n+1) { |i| i }
primes = [2]
nn = 2
dif = n-1-k
while dif > 1
	seq[nn], seq[nn+1] = seq[nn+1], seq[nn]
	nn+=2
	dif -= 2
end
if dif == 1
	seq[1] = nn
	seq[nn] = 1
end
seq[1..-1].each{|i| print "#{i} "}

n,k=gets.chomp.split.map(&:to_i)
if n==k
	puts "-1";exit
end
print n-k
(n-k-1).times{|i| print " #{i+1}"}
for i in n-k+1..n
	print " #{i}"
end
puts

class B
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    count = n-1
    index = 1

    answer = (1..n).to_a

    if n <= k
      puts -1
      exit
    end

    if ( (count.odd? && k.even?) || (count.even? && k.odd? ) )
      answer[0], answer[1] = answer[1], answer[0]
      count -= 1
      index = 2
    end

    while count != k && index < n
      answer[index], answer[index+1] = answer[index+1], answer[index]
      count -= 2
      index += 2
    end

    if count == k
      puts answer.join(' ')
    else
      puts -1
    end
  end
end

b = B.new

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

if n == k
  puts "-1"
  exit
end

arr = (1..n).to_a
ck = n - 1
arr.each_with_index { |e , i|
  break if ck == k
  arr[0], arr[n - i - 1] = arr[n - i - 1], arr[0]
  ck -= 1
}

puts arr.join(' ')

n,k = gets.split(" ").map(&:to_i)
bad = n - k
perm = (2..bad).to_a
perm.push(1)
perm.push(*((bad+1)..(bad+k)))
if n == k
	puts "-1"
else
puts perm.join(" ")
end

n, k = gets.chomp.split(' ').collect {|x| x.to_i}

q = n-k

if q < 1
  puts -1
elsif q == 1
  puts (1..n).to_a.join ' '
else
  arr = (1..(q-1)).to_a
  arr = [q] + arr
  arr = arr + ((q+1)..n).to_a
  puts arr.join ' '
end

line = gets.chomp.split(" ").map { |e| e.to_i }
n = line[0]
k = line[1]

if n == k
  puts "-1"
elsif n == k + 1
  for i in 1..n
    print(i.to_s + " ")
  end
  puts
else
  print((k+2).to_s + " ")
  for i in 2..n
    if i != k+2
      print(i.to_s + " ")
    end
  end
  print("1\n")
end

class B
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    count = n-1

    answer = (1..n).to_a

    if n <= k
      puts -1
      exit
    end

    if k.even?
      answer[0], answer[1] = answer[1], answer[0]
      count -= 1
    end

    index = 2
    while count != k && index < n
      answer[index], answer[index+1] = answer[index+1], answer[index]
      count -= 2
      index += 2
    end

    if count == k
      puts answer.join(' ')
    else
      puts -1
    end
  end
end

b = B.new

class B
  def initialize
    n, k = gets.chomp.split(' ').map(&:to_i)
    count = n-1
    index = 1

    answer = (1..n).to_a

    if n <= k
      puts -1
      exit
    end

    if !k.zero? && ( (count.odd? && k.even?) || (count.even? && k.odd? ) )
      answer[0], answer[1] = answer[1], answer[0]
      count -= 1
      index = 2
    end

    while count != k && index < n
      answer[index], answer[index+1] = answer[index+1], answer[index]
      count -= 2
      index += 2
    end

    if count == k
      puts answer.join(' ')
    else
      puts -1
    end
  end
end

b = B.new

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

if n == k
  puts "-1"
  exit
end

arr = (1..n).to_a
ck = n - 1
arr.each_with_index { |e , i|
  break if ck == k
  i += 1 if i.odd?
  arr[i], arr[n - 1] = arr[n - 1], arr[i]
  ck -= 1
}

puts arr.join(' ')

n,k = gets.split(" ").map(&:to_i)
bad = n - k
perm = (2..bad).to_a
perm.push(1)
perm.push(*((bad+1)..(bad+k)))
if n == 1
	puts "-1"
else
puts perm.join(" ")
end

n,k = gets.split(" ").map(&:to_i)
bad = n - k
perm = (2..bad).to_a
perm.push(1)
perm.push(*((bad+1)..(bad+k)))
if n == 1 && k == 1
	puts "-1"
else
puts perm.join(" ")
end

n,k = gets.split(" ").map(&:to_i)
bad = n - k
perm = (1..bad).to_a
perm.push(*((bad+2)..(bad+k)))
perm.push(bad+1)
if n == 1
	puts "-1"
else
puts perm.join(" ")
end


You play your favourite game yet another time. You chose the character you didn't play before. It has $$$str$$$ points of strength and $$$int$$$ points of intelligence. Also, at start, the character has $$$exp$$$ free experience points you can invest either in strength or in intelligence (by investing one point you can either raise strength by $$$1$$$ or raise intelligence by $$$1$$$).Since you'd like to make some fun you want to create a jock character, so it has more strength than intelligence points (resulting strength is strictly greater than the resulting intelligence).Calculate the number of different character builds you can create (for the purpose of replayability) if you must invest all free points. Two character builds are different if their strength and/or intellect are different.

The first line contains the single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$T$$$ lines contain descriptions of queries — one per line. This line contains three integers $$$str$$$, $$$int$$$ and $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) — the initial strength and intelligence of the character and the number of free points, respectively.

Print $$$T$$$ integers — one per query. For each query print the number of different character builds you can create.

NoteIn the first query there are only three appropriate character builds: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ and $$$(9, 3)$$$. All other builds are either too smart or don't use all free points.In the second query there is only one possible build: $$$(2, 1)$$$.In the third query there are two appropriate builds: $$$(7, 6)$$$, $$$(8, 5)$$$.In the fourth query all builds have too much brains.

gets.to_i.times do
    s,t,e = gets.split.map(&:to_i)
    if s+e <= t
        puts 0
    else
        b = (t+e-s)/2
        puts e-(b > -2 ? b : -1)
    end
end

t = STDIN.readline.to_i

t.times {
    str, int, exp = STDIN.readline.split.map &:to_i
    if str+exp <= int
        p 0
        next
    end

    if (d = int-str) > 0
        str = int
        exp -= d
    end

    int += exp
    i = (0..exp).bsearch do |e|
        str+e > int-e
    end
    p exp-i+1
}

tt = gets.chomp.to_i
tt.times.map do
  str, int, exp = gets.split.map(&:to_i)
  diff = str - int

  cnt = 0
  if diff<0
    exp += diff
    if exp<=0
    else
      cnt+=(exp+1)/2
    end
  elsif diff==0
    cnt+=(exp+1)/2
  else
    if exp < diff
      cnt+=exp+1
    else
      cnt+=(exp+diff+1)/2
    end
  end

  puts cnt
end

t = gets.chomp.to_i

t.times do |i|
  str, int, exp = gets.chomp.split.map(&:to_i)
  diff = str + exp - int
  if diff <= 0
    puts 0
  else
    puts [(diff+1)/2, exp+1].min
  end
end

gets.to_i.times do
    s,t,e = gets.split.map(&:to_i)
    if s+e <= t
        puts 0
    else
        puts s+e-(s+(t+e-s)/2)
    end
end

gets.to_i.times do
    s,t,e = gets.split.map(&:to_i)
    if s+e <= t
        puts 0
    else
        b = (t+e-s)/2
        if e > 0
            puts e-(b > 0 ? b : 0)
        else
            puts 1
        end
    end
end

t = gets.chomp.to_i

t.times do |i|
  str, int, exp = gets.chomp.split.map(&:to_i)
  # str + a > int + b
  # a + b = exp
  # str + exp > int + 2b
  # 2b <= str + exp - int + 1
  # b >= 0
  diff = [str + exp - int + 1, 0].max
  puts diff/2
end

t = gets.chomp.to_i

t.times do |i|
  str, int, exp = gets.chomp.split.map(&:to_i)
  cut = (exp+int-str)/2 + 1
  puts [exp-cut+1, 0].max
end

t = gets.chomp.to_i

t.times do |i|
  str, int, exp = gets.chomp.split.map(&:to_i)
  diff = str + exp - int
  if diff <= 0
    puts 0
  else
    puts (diff+1)/2
  end
end


There were $$$n$$$ types of swords in the theater basement which had been used during the plays. Moreover there were exactly $$$x$$$ swords of each type. $$$y$$$ people have broken into the theater basement and each of them has taken exactly $$$z$$$ swords of some single type. Note that different people might have taken different types of swords. Note that the values $$$x, y$$$ and $$$z$$$ are unknown for you.The next morning the director of the theater discovers the loss. He counts all swords — exactly $$$a_i$$$ swords of the $$$i$$$-th type are left untouched.The director has no clue about the initial number of swords of each type in the basement, the number of people who have broken into the basement and how many swords each of them have taken.For example, if $$$n=3$$$, $$$a = [3, 12, 6]$$$ then one of the possible situations is $$$x=12$$$, $$$y=5$$$ and $$$z=3$$$. Then the first three people took swords of the first type and the other two people took swords of the third type. Note that you don't know values $$$x, y$$$ and $$$z$$$ beforehand but know values of $$$n$$$ and $$$a$$$.Thus he seeks for your help. Determine the minimum number of people $$$y$$$, which could have broken into the theater basement, and the number of swords $$$z$$$ each of them has taken.

The first line of the input contains one integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of types of swords. The second line of the input contains the sequence $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^{9})$$$, where $$$a_i$$$ equals to the number of swords of the $$$i$$$-th type, which have remained in the basement after the theft. It is guaranteed that there exists at least one such pair of indices $$$(j, k)$$$ that $$$a_j \neq a_k$$$.

Print two integers $$$y$$$ and $$$z$$$ — the minimum number of people which could have broken into the basement and the number of swords each of them has taken.

NoteIn the first example the minimum value of $$$y$$$ equals to $$$5$$$, i.e. the minimum number of people who could have broken into the basement, is $$$5$$$. Each of them has taken $$$3$$$ swords: three of them have taken $$$3$$$ swords of the first type, and two others have taken $$$3$$$ swords of the third type.In the second example the minimum value of $$$y$$$ is $$$1$$$, i.e. the minimum number of people who could have broken into the basement, equals to $$$1$$$. He has taken $$$7$$$ swords of the first type.

n = gets.chomp.to_i
arr = gets.chomp.split(' ').map(&:to_i)
mx = arr.max
arr = arr.map{|el| mx - el}
m = arr.reduce(arr[0].gcd(arr[1]), :gcd)
res = 0
arr.each do |el|
  res += el / m
end
puts [res, m].join(' ')

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

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

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

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
n=gi
a=desc gsmi
max=a.shift
putsend("0 0") if max==0
a.map!{|i|max-i}

z=a[-1]
putsend("0 0") if z==0
0.upto(a.size-1-1) do |i|
  z = z.gcd(a[i])
end
0.upto(a.size-1) do |i|
  cnt+=a[i]/z
end
puts "#{cnt} #{z}"


Bessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However, Bessie is sure that there is a secret message hidden inside.The text is a string $$$s$$$ of lowercase Latin letters. She considers a string $$$t$$$ as hidden in string $$$s$$$ if $$$t$$$ exists as a subsequence of $$$s$$$ whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices $$$1$$$, $$$3$$$, and $$$5$$$, which form an arithmetic progression with a common difference of $$$2$$$. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of $$$S$$$ are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden $$$3$$$ times, b is hidden $$$2$$$ times, ab is hidden $$$6$$$ times, aa is hidden $$$3$$$ times, bb is hidden $$$1$$$ time, aab is hidden $$$2$$$ times, aaa is hidden $$$1$$$ time, abb is hidden $$$1$$$ time, aaab is hidden $$$1$$$ time, aabb is hidden $$$1$$$ time, and aaabb is hidden $$$1$$$ time. The number of occurrences of the secret message is $$$6$$$.

The first line contains a string $$$s$$$ of lowercase Latin letters ($$$1 \le |s| \le 10^5$$$) — the text that Bessie intercepted.

Output a single integer  — the number of occurrences of the secret message.

NoteIn the first example, these are all the hidden strings and their indice sets:   a occurs at $$$(1)$$$, $$$(2)$$$, $$$(3)$$$  b occurs at $$$(4)$$$, $$$(5)$$$  ab occurs at $$$(1,4)$$$, $$$(1,5)$$$, $$$(2,4)$$$, $$$(2,5)$$$, $$$(3,4)$$$, $$$(3,5)$$$  aa occurs at $$$(1,2)$$$, $$$(1,3)$$$, $$$(2,3)$$$  bb occurs at $$$(4,5)$$$  aab occurs at $$$(1,3,5)$$$, $$$(2,3,4)$$$  aaa occurs at $$$(1,2,3)$$$  abb occurs at $$$(3,4,5)$$$  aaab occurs at $$$(1,2,3,4)$$$  aabb occurs at $$$(2,3,4,5)$$$  aaabb occurs at $$$(1,2,3,4,5)$$$  Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.

S = gets.chomp

counter = Hash.new(0)
sum = Hash.new(0)

S.each_char do |s|
  counter.each do |c, cnt|
    sum[c + s] += cnt
  end

  counter[s] += 1
end

puts [counter.values.max, sum.values.max || 0].max


Among other things, Bob is keen on photography. Especially he likes to take pictures of sportsmen. That was the reason why he placed himself in position x0 of a long straight racetrack and got ready to take pictures. But the problem was that not all the runners passed him. The total amount of sportsmen, training at that racetrack, equals n. And each of them regularly runs distances within a particular segment of the racetrack, which is the same for each sportsman. For example, the first sportsman runs from position a1 to position b1, the second — from a2 to b2What is the minimum distance that Bob should move to have a chance to take pictures of each sportsman? Bob can take a picture of a sportsman, if he stands within the segment that this sportsman covers on the racetrack.

The first line of the input file contains integers n and x0 (1 ≤ n ≤ 100; 0 ≤ x0 ≤ 1000). The following n lines contain pairs of integers ai, bi (0 ≤ ai, bi ≤ 1000; ai ≠ bi).

Output the required minimum distance in the same units as the positions on the racetrack. If there is no such a position, output -1.

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i

mx1 = -1
mx2 = 1001
for i in 0..n-1
	x1s, x2s = gets.chomp.split(/ /)
	x1 = x1s.to_i
	x2 = x2s.to_i
	ax = [x1,x2].max
	ix = [x1,x2].min
	mx1 = [mx1, ix].max
	mx2 = [mx2, ax].min
end
if mx1 > mx2
	puts "-1"
else
	ret = 0
	if m < mx1 || m > mx2
		ret= [(mx1-m).abs, (mx2-m).abs].min
	end
	puts ret
end

class Range
	def ^(other)
		([first, other.first].max .. [last, other.last].min)
	end
end

n, x0 = gets.split.map{|i| i.to_i}
r = []
n.times do
	a, b = gets.split.map{|i| i.to_i}
	a, b = b, a if a > b
	r <<= (a .. b)
end
r = r.inject{|i, j| i ^ j}

unless r.first <= r.last then
	p -1
else
	p r.include?(x0) ? 0 : [(r.first - x0).abs, (r.last - x0).abs].min
end

n,x=gets.split.map(&:to_i)
sum=Array.new(1002,0)
tsum=Array.new(1002,0)
n.times{
        a,b=gets.split.map(&:to_i).sort
        b+=1
        tsum[a]+=1
        tsum[b]-=1
}
sum[0]=tsum[0]
ans=[]
ans.push(x) if sum[0]==n
1.upto(1001){|i|
        sum[i]=sum[i-1]+tsum[i]
        if sum[i]==n then
                ans.push((x-i).abs)
        end
}
ans.push(-1) if ans.size()==0

p ans.min

#Inf = Float::Infinity
#
#geti
#getia(delimiter = " ")
#
#Object # dcopy
#
#String # to_a
#   "abc".to_a #=> ["a","b","c"]
#String # to_ia
#   "1 2 3".to_ia #=> [1,2,3]
#

include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Inf = Float::INFINITY
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;
             def to_ia(d = " ");split(d).map(&:to_i);end;end
def getia(*arg);gets.to_ia(*arg);end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end

n, q = getia
c = [0] * 2000
n.times do
  a, b = getia.sort
  for i in a..b
    c[i] += 1
  end
end
res = Inf
for i in 0..1010
  if c[i] == n
    res = [(i-q).abs, res].min
  end
end
puts res == Inf ? -1 : res

n,x = gets.split.map(&:to_i)
lmax = 0
rmin = 1000
n.times do |i|
  a,b = gets.split.map(&:to_i)
  if a > b then a,b = b,a end
  if a > lmax then lmax = a end
  if b < rmin then rmin = b end
end
#p lmax
#p rmin
if rmin < lmax then
  print -1
  elsif x < lmax then
  print lmax - x
  elsif x > rmin then
  print x - rmin
  else
  print 0
end
puts

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

seg_start = 0
seg_end = 1000
n.times do
	a, b = gets.split.map(&:to_i)
	a, b = b, a if a > b
	seg_start = a if a > seg_start
	seg_end = b if b < seg_end
end

if seg_end < seg_start
	puts -1
elsif seg_start < x && x < seg_end
	puts 0
else
	puts [(seg_start - x).abs, (seg_end - x).abs].min
end

# require 'set'
# n, x = gets.split.map(&:to_i)

# input = []
# n.times do
# 	input << gets.split.map(&:to_i)
# end

# interval = (input[0].min..input[0].max).to_set
# input.each do |segment|
# 	interval = interval & (segment.min..segment.max).to_set
# end
# if interval.empty?
# 	puts -1
# else
# 	puts interval.include?(x) ? 0 : [(interval.min - x).abs, (interval.max - x).abs].min
# end

require 'set'
n, x = gets.chomp!.split.map(&:to_i)

input = []
n.times do
	input << gets.chomp!.split.map(&:to_i)
end

interval = (input[0].min..input[0].max).to_set
input.each do |segment|
	interval = interval & (segment.min..segment.max).to_set
end
if interval.empty?
	puts -1
else
	puts interval.include?(x) ? 0 : [(interval.min - x).abs, (interval.max - x).abs].min
end

n,x = gets.split(" ").map(&:to_i)
start = -1
finish = 2000
n.times do
	a,b = gets.split(" ").map(&:to_i).minmax
	start = a if a > start
	finish = b if b < finish
end
ans = (start..finish).map{|a| (a-x).abs }.min
ans ||= -1
# puts "#{start} #{finish}"
puts "#{ans}"

# 3 3
# 0 7
# 8 10
# 11 13

n,d = gets.chomp!.split.map(&:to_i)
left,right = -1,1001
n.times do |x|
    a,b = gets.chomp!.split.map(&:to_i)
    a,b = [a,b].min,[a,b].max
    left = a if a > left
    right = b if b < right
end

ans = [left > d ? left-d : 0, right < d ? d-right : 0].max
ans = -1 if left > right
puts ans

#!/usr/bin/env ruby

n, x0 = gets.split.map(&:to_i)
x, y = -1000, 1000
n.times do
	a, b = gets.split.map(&:to_i)
	a, b = b, a if a > b
	x, y = [x, a].max, [y, b].min
end
puts x > y ? -1 : (x <= x0 && x0 <= y ? 0 : [x - x0, x0 - y].max)

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i

ret = 0
for i in 0..n-1
	x1s, x2s = gets.chomp.split(/ /)
	x1 = x1s.to_i
	x2 = x2s.to_i
	ax = [x1,x2].max
	ix = [x1,x2].min
	if m < ix
		ret = [ix-m, ret].max
	end
	if m > ax
		ret = [m-ax, ret].max
	end
end
puts ret

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i

ret = -1
for i in 0..n-1
	x1s, x2s = gets.chomp.split(/ /)
	x1 = x1s.to_i
	x2 = x2s.to_i
	ax = [x1,x2].max
	ix = [x1,x2].min
	if m < ix
		ret = [ix-m, ret].max
	end
	if m > ax
		ret = [m-ax, ret].max
	end
end
puts ret

ns,ms = gets.chomp.split(/ /)
n = ns.to_i
m = ms.to_i

mx1 = -1
mx2 = 1001
for i in 0..n-1
	x1s, x2s = gets.chomp.split(/ /)
	x1 = x1s.to_i
	x2 = x2s.to_i
	ax = [x1,x2].max
	ix = [x1,x2].min
	mx1 = [mx1, ix].max
	mx2 = [mx2, ax].min
end
if mx1 > mx2
	puts "-1"
else
	puts [(mx1-m).abs, (mx2-m).abs].min
end

class Range
	def ^(other)
		Range.new([first, other.first].max, [last, other.last].min)
	end
end

n, x0 = gets.split.map{|i| i.to_i}
r = []
n.times do
	a, b = gets.split.map{|i| i.to_i}
	a, b = b, a if a > b
	r <<= (a .. b)
end
r = r.inject{|i, j| i ^ j}

unless r.first < r.last then
	p -1
else
	p r.include?(x0) ? 0 : [(r.first - x0).abs, (r.last - x0).abs].min
end

n,d = gets.chomp!.split.map(&:to_i)
left,right = [],[]
n.times do |x|
    a,b = gets.chomp!.split.map(&:to_i)
    left << [a,b].min
    right << [a,b].max
end

ans1 = left.max > d ? left.max - d : 0
ans2 = right.min < d ? d - right.min : 0
puts [ans1,ans2].max

#!/usr/bin/env ruby

n, x0 = gets.split.map(&:to_i)
mn, mx = x0, x0
n.times do
	a, b = gets.split.map(&:to_i)
	a, b = b, a if a > b
	mx = [mx, a].max if a > x0
	mn = [mn, b].min if b < x0
end
puts mx - mn + [x0 - mn, mx - x0].min


Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to learn those letters. That's why he decided to lose some part of the string (not necessarily a connected part). The lost part can consist of any number of segments of any length, at any distance from each other. However, Gerald knows that if he loses more than k characters, it will be very suspicious. Find the least number of distinct characters that can remain in the string after no more than k characters are deleted. You also have to find any possible way to delete the characters.

The first input data line contains a string whose length is equal to n (1 ≤ n ≤ 105). The string consists of lowercase Latin letters. The second line contains the number k (0 ≤ k ≤ 105).

Print on the first line the only number m — the least possible number of different characters that could remain in the given string after it loses no more than k characters. Print on the second line the string that Gerald can get after some characters are lost. The string should have exactly m distinct characters. The final string should be the subsequence of the initial string. If Gerald can get several different strings with exactly m distinct characters, print any of them.

NoteIn the first sample the string consists of five identical letters but you are only allowed to delete 4 of them so that there was at least one letter left. Thus, the right answer is 1 and any string consisting of characters "a" from 1 to 5 in length.In the second sample you are allowed to delete 4 characters. You cannot delete all the characters, because the string has length equal to 7. However, you can delete all characters apart from "a" (as they are no more than four), which will result in the "aaaa" string.In the third sample you are given a line whose length is equal to 8, and k = 10, so that the whole line can be deleted. The correct answer is 0 and an empty string.

#!ruby

str = STDIN.gets.strip
k = STDIN.gets.strip.to_i

charnums = Hash.new(0)

str.each_byte do |c|
    charnums[c] += 1
end

delchar = []

charnums.to_a.sort do |a,b|
    (a[1] <=> b[1]) * 2 + (b[0] <=> a[0])
end.each do |elem|
    if elem[1] <= k
        delchar << elem[0]
        k -= elem[1]
    else
        break
    end
end

delchar.each do |c|
    str.delete!("%c"%c)
end

puts str.unpack("C*").uniq.length
puts str

s = gets.chomp
n = gets.to_i
a = s.split(//).uniq
b = []
a.each { |x| b << s.count(x) }
while (n - b.min) >= 0
  n -= b.min
  s.delete!(a[b.index(b.min)])
  b[b.index(b.min)] = 9999999999999999
  break if s.empty? || b.empty?
end
puts s.split(//).uniq.size
puts s

#!ruby

str = STDIN.gets.strip
k = STDIN.gets.strip.to_i

charnums = Hash.new(0)

str.each_byte do |c|
    charnums[c] += 1
end

delchar = []

charnums.to_a.sort do |a,b|
    (a[1] <=> b[1]) * 2 + (b[0] <=> a[0])
end.each do |elem|
    if elem[1] < k
        delchar << elem[0]
        k -= elem[1]
    else
        break
    end
end

delchar.each do |c|
    str.delete!("%c"%c)
end

puts str.unpack("C*").uniq.length
puts str


The semester is already ending, so Danil made an effort and decided to visit a lesson on harmony analysis to know how does the professor look like, at least. Danil was very bored on this lesson until the teacher gave the group a simple task: find 4 vectors in 4-dimensional space, such that every coordinate of every vector is 1 or  - 1 and any two vectors are orthogonal. Just as a reminder, two vectors in n-dimensional space are considered to be orthogonal if and only if their scalar product is equal to zero, that is: .Danil quickly managed to come up with the solution for this problem and the teacher noticed that the problem can be solved in a more general case for 2k vectors in 2k-dimensinoal space. When Danil came home, he quickly came up with the solution for this problem. Can you cope with it?

The only line of the input contains a single integer k (0 ≤ k ≤ 9).

Print 2k lines consisting of 2k characters each. The j-th character of the i-th line must be equal to ' * ' if the j-th coordinate of the i-th vector is equal to  - 1, and must be equal to ' + ' if it's equal to  + 1. It's guaranteed that the answer always exists. If there are many correct answers, print any.

NoteConsider all scalar products in example:  Vectors 1 and 2: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( + 1) + ( - 1)·( - 1) = 0  Vectors 1 and 3: ( + 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 1 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( - 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 2 and 3: ( + 1)·( + 1) + ( - 1)·( + 1) + ( + 1)·( + 1) + ( - 1)·( + 1) = 0  Vectors 2 and 4: ( + 1)·( + 1) + ( - 1)·( - 1) + ( + 1)·( - 1) + ( - 1)·( + 1) = 0  Vectors 3 and 4: ( + 1)·( + 1) + ( + 1)·( - 1) + ( + 1)·( - 1) + ( + 1)·( + 1) = 0

n = gets.to_i

flip = ->(s) { s.each_char.map { |c| c == '+' ? '*' : '+'}.join }

if n == 0 then
  puts "+"
else
  ans = []
  ans[1] = ["++", "+*"]

  (2..n).each do |i|
    k = 2**i
    ans[i] = ans[i - 1].dup
    (k/2).times do |j|
      if j.even? then
        ans[i][j] += flip.(ans[i][j])
      else
        ans[i][j] += ans[i][j]
      end
    end
    (k/2).times do |j|
      ans[i] << ans[i - 1][j].reverse
    end
    ((k/2)...k).each do |j|
      if j.odd? then
        ans[i][j] = flip.(ans[i][j]) + ans[i][j]
      else
        ans[i][j] = ans[i][j] + ans[i][j]
      end
    end
  end

  puts ans[n]
end

n = gets.chomp.to_i

as = ['+']

def f(as)
  bs = []
  as.each do |a|
    b = ''
    for i in 0...a.size
      if a[i] == '+'
        b += '++'
      else
        b += '**'
      end
    end
    bs << b
  end
  as.each do |a|
    b = ''
    for i in 0...a.size
      if a[i] == '+'
        b += '+*'
      else
        b += '*+'
      end
    end
    bs << b
  end
  return bs
end

for i in 1..n
  as = f(as)
end

puts as.*"\n"


The World Programming Olympics Medal is a metal disk, consisting of two parts: the first part is a ring with outer radius of r1 cm, inner radius of r2 cm, (0 < r2 < r1) made of metal with density p1 g/cm3. The second part is an inner disk with radius r2 cm, it is made of metal with density p2 g/cm3. The disk is nested inside the ring.The Olympic jury decided that r1 will take one of possible values of x1, x2, ..., xn. It is up to jury to decide which particular value r1 will take. Similarly, the Olympic jury decided that p1 will take one of possible value of y1, y2, ..., ym, and p2 will take a value from list z1, z2, ..., zk.According to most ancient traditions the ratio between the outer ring mass mout and the inner disk mass min must equal , where A, B are constants taken from ancient books. Now, to start making medals, the jury needs to take values for r1, p1, p2 and calculate the suitable value of r2.The jury wants to choose the value that would maximize radius r2. Help the jury find the sought value of r2. Value r2 doesn't have to be an integer.Medal has a uniform thickness throughout the area, the thickness of the inner disk is the same as the thickness of the outer ring.

The first input line contains an integer n and a sequence of integers x1, x2, ..., xn. The second input line contains an integer m and a sequence of integers y1, y2, ..., ym. The third input line contains an integer k and a sequence of integers z1, z2, ..., zk. The last line contains two integers A and B. All numbers given in the input are positive and do not exceed 5000. Each of the three sequences contains distinct numbers. The numbers in the lines are separated by spaces.

Print a single real number — the sought value r2 with absolute or relative error of at most 10 - 6. It is guaranteed that the solution that meets the problem requirements exists.

NoteIn the first sample the jury should choose the following values: r1 = 3, p1 = 2, p2 = 1.

gets " "
xs = gets.split.map(&:to_i).sort
gets " "
ys = gets.split.map(&:to_i).sort
gets " "
zs = gets.split.map(&:to_i).sort
a,b = gets.split.map(&:to_i)

#p [a,b]
#r1 = xs.max
p1 = ys.max
p2 = zs.min

for r1 in xs.reverse
    r2 = r1/Math::sqrt(1.0*a/b*p2/p1+1)
    #p [r1,r2,p1,p2]
    #p p1*(1.0*r1*r1/r2/r2 - 1)/p2
    break puts r2 if r2 < r1
end

x = gets.split.map(&:to_i)[1..-1].max
y = gets.split.map(&:to_i)[1..-1].max
z = gets.split.map(&:to_i)[1..-1].min
A, B = gets.split.map(&:to_i)
p Math.sqrt((x * x * y * B * 1.0 ) / (A * z + y * B))

a=gets.split.map(&:to_i)[1..-1].max;
b=gets.split.map(&:to_i)[1..-1].max;
c=gets.split.map(&:to_i)[1..-1].min;
d,e=gets.split.map &:to_f;
p (a*a*b*e/(c*d+b*e))**0.5

r1 = gets.split.map(&:to_f).slice!(1..-1).max
ro1 = gets.split.map(&:to_f).slice!(1..-1).max
ro2 = gets.split.map(&:to_f).slice!(1..-1).min
a, b = gets.split.map(&:to_f)

puts Math.sqrt((r1*r1*b*ro1)/(b*ro1+a*ro2))


You are given a string, consisting of lowercase Latin letters.A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions $$$(1, 2)$$$ — "ab" and $$$(2, 3)$$$ — "ba". Letters 'a' and 'z' aren't considered neighbouring in a alphabet.Can you rearrange the letters of a given string so that there are no ugly pairs? You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same.If there are multiple answers, print any of them.You also have to answer $$$T$$$ separate queries.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Each of the next $$$T$$$ lines contains string $$$s$$$ $$$(1 \le |s| \le 100)$$$ — the string for the next query. It is guaranteed that it contains only lowercase Latin letters. Note that in hacks you have to set $$$T = 1$$$.

Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th query. If the answer for the $$$i$$$-th query exists, then print such a rearrangment of letters of the given string that it contains no ugly pairs. You can choose any order of the letters of the given string but you can't add any new letters or remove the existing ones. You can also leave the order the same. If there are multiple answers, print any of them. Otherwise print "No answer" for that query.

NoteIn the first example answer "bdac" is also correct.The second example showcases the fact that only neighbouring in alphabet letters are not allowed. The same letter is ok.There are lots of valid answers for the third example.

alphabet = {"a"=>0,"b"=>1,"c"=>2,"d"=>3,"e"=>4,"f"=>5,"g"=>6,"h"=>7,"i"=>8,"j"=>9,"k"=>10,"l"=>11,"m"=>12,"n"=>13,"o"=>14,"p"=>15,"q"=>16,"r"=>17,"s"=>18,"t"=>19,"u"=>20,"v"=>21,"w"=>22,"x"=>23,"y"=>24,"z"=>25}

n = gets.to_i

n.times do
  cnt = [0]*26
  kind = []
  s = gets.chomp
  s.each_char do |c|
    cnt[alphabet[c]] += 1
    kind << alphabet[c]
  end

  kind.uniq!
  kind.sort!
  l = kind.length
  ans = [""]*26
  if l == 2
    replace = [0,1]
  elsif l == 3
    replace =  (kind[1] - kind[0] == 1) ? [0,2,1] : [1,0,2]
  elsif l == 4
    replace = [1,3,0,2]
  else
    replace = []*l
    t = [(l+2)/3,(l+1)/3,l/3]
    k = 0
    3.times do |i|
      t[i].times do |j|
        replace[j*3+i] = j + k
      end
      k += t[i]
    end
  end
  replace.each_with_index do |v,i|
    ans[v] = alphabet.key(kind[i]) * cnt[kind[i]]
  end

  ans = ans.join
  (s.length-1).times do |i|
    if (alphabet[ans[i]] - alphabet[ans[i+1]]).abs == 1
      ans = "No answer"
      break
    end
  end
  puts ans
end

gets.to_i.times do
    a,b=gets.chomp.chars.sort.partition{|e|e.ord.odd?}.map(&:join)
    ok=->x,y{ x.empty? or y.empty? or (x[-1].ord-y[0].ord).abs!=1 }
    puts (ok[a, b] ? a+b : ok[b, a] ? b+a : "No answer")
end

t = gets.to_i
t.times do
  s = gets.strip.chars.sort.join
  t = ''
  stk = []
  iter = 0
  until s.empty? && stk.empty?
    unless stk.empty?
      c = stk.shift
      if t.empty? || (t[-1].ord - c.ord).abs != 1
        t += c
      elsif (t[0].ord - c.ord).abs != 1
        t = c + t
      else
        stk.push(c)
      end
    end
    unless s.empty?
      c = s[0]
      s = s[1..-1]
      if t.empty? || (t[-1].ord - c.ord).abs != 1
        t += c
      elsif (t[0].ord - c.ord).abs != 1
        t = c + t
      else
        stk.push(c)
      end
    end
    iter += 1
    if iter == 2000
      t = "No answer"
      break
    end
  end
  puts t
end

n = gets.chomp.to_i

def adjacent?(a,b)
  (a.ord - b.ord).abs == 1
end

def order(str)
  a, b = str.split(//).sort.partition {|c| c.ord.odd? }
  if a.empty? || b.empty?
    a.join + b.join
  elsif !adjacent?(a.first, b.last)
    b.join + a.join
  elsif !adjacent?(a.last, b.first)
    a.join + b.join
  else
    'No answer'
  end
end

n.times do
  str = gets.chomp
  puts order(str)
end

alphabet = {"a"=>0,"b"=>1,"c"=>2,"d"=>3,"e"=>4,"f"=>5,"g"=>6,"h"=>7,"i"=>8,"j"=>9,"k"=>10,"l"=>11,"m"=>12,"n"=>13,"o"=>14,"p"=>15,"q"=>16,"r"=>17,"s"=>18,"t"=>19,"u"=>20,"v"=>21,"w"=>22,"x"=>23,"y"=>24,"z"=>25}

n = gets.to_i
replace = [2,0,3,1]
n.times do
  cnt = [0]*26
  kind = []
  s = gets.chomp
  s.each_char do |c|
    cnt[alphabet[c]] += 1
    kind << alphabet[c]
  end
  t = 0

  kind.uniq!
  kind.sort!

  ans = [""]*26
  if kind.length == 3
    [0,2,1].each_with_index do |v,i|
      ans[v] = alphabet.key(kind[i]) * cnt[kind[i]]
    end
  else
    26.times do |i|
      if cnt[i] > 0
        ans[(t/4)*4 + replace[t%4]] = alphabet.key(i) * cnt[i]
        t += 1
      end
    end
  end
  #p ans
  ans = ans.join
  (s.length-1).times do |i|
    if (alphabet[ans[i]] - alphabet[ans[i+1]]).abs == 1
      ans = "No answer"
      break
    end
  end
  puts ans
end


Vasya learns to type. He has an unusual keyboard at his disposal: it is rectangular and it has n rows of keys containing m keys in each row. Besides, the keys are of two types. Some of the keys have lowercase Latin letters on them and some of the keys work like the "Shift" key on standard keyboards, that is, they make lowercase letters uppercase.Vasya can press one or two keys with one hand. However, he can only press two keys if the Euclidean distance between the centers of the keys does not exceed x. The keys are considered as squares with a side equal to 1. There are no empty spaces between neighbouring keys.Vasya is a very lazy boy, that's why he tries to type with one hand as he eats chips with his other one. However, it is possible that some symbol can't be typed with one hand only, because the distance between it and the closest "Shift" key is strictly larger than x. In this case he will have to use his other hand. Having typed the symbol, Vasya returns other hand back to the chips.You are given Vasya's keyboard and the text. Count the minimum number of times Vasya will have to use the other hand.

The first line contains three integers n, m, x (1 ≤ n, m ≤ 30, 1 ≤ x ≤ 50). Next n lines contain descriptions of all the keyboard keys. Each line contains the descriptions of exactly m keys, without spaces. The letter keys are marked with the corresponding lowercase letters. The "Shift" keys are marked with the "S" symbol.  Then follow the length of the text q (1 ≤ q ≤ 5·105). The last line contains the text T, which consists of q symbols, which are uppercase and lowercase Latin letters.

If Vasya can type the text, then print the minimum number of times he will have to use his other hand. Otherwise, print "-1" (without the quotes).

3 9 4
qwertyuio
asdfghjkl
SzxcvbnmS
35
TheQuIcKbRoWnFOXjummsovertHeLazYDOG

NoteIn the first sample the symbol "A" is impossible to print as there's no "Shift" key on the keyboard.In the second sample the symbol "e" is impossible to print as there's no such key on the keyboard.In the fourth sample the symbols "T", "G" are impossible to print with one hand. The other letters that are on the keyboard can be printed. Those symbols come up in the text twice, thus, the answer is 2.

class Point
	attr_accessor :x
	attr_accessor :y

	def initialize(x1,y1)
    	@x = x1.to_f
    	@y = y1.to_f
  	end

	def distance_to(x1,y1)
    	dx = @x - x1
    	dy = @y - y1
    	d = Math.sqrt(dx * dx + dy * dy)
    	return(d)
  	end
end

n,m,xx = gets.chomp.split(/ /).map!{|x| x.to_i}
bbb = []
sss = []
mmm = Hash::new
mmm.default = -1
for i in 0..n-1
	bbb.push(gets.chomp)
	for j in 0..m-1
		sss.push(Point.new(j,i)) if bbb[i][j] == "S"
	end
end

for i in 0..n-1
	for j in 0..m-1
		if bbb[i][j] != "S" then
			wk = mmm[bbb[i][j]]
			sss.each{|x|
				wk2 = x.distance_to(j,i)
				if wk < 0 then
					wk = wk2
				else
					wk = wk2 if wk > wk2
				end
			}
			mmm[bbb[i][j]] = wk
		end
	end
end
q = gets.chomp.to_i
t = gets.chomp

ret = 0
t.each_byte{|x|
	x = x.chr
	if mmm.key?(x.downcase) == false then
		ret = -1
		break
	end
	if x.upcase == x then
		x.downcase!
		if mmm[x] < 0 then
			ret = -1
			break
		end
		ret += 1 if xx < mmm[x]
	end
}

puts ret

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

  has_shift = false
  kb=[]
  n.times{
    l = gets.chomp
    kb << l
    has_shift |= (l =~ /S/)
  }
  alphabets = (kb * '').gsub('S', '')

  need_two = {}
  n.times{|y1|
    m.times{|x1|
      next if kb[y1][x1] != ?S
      n.times{|y2|
        m.times{|x2|
          c = kb[y2][x2]
          next if c == ?S

          dist2 = (y2-y1)**2 + (x2-x1)**2
          need_two[c] = [need_two[c] || 99999999, dist2].min
        }
      }
    }
  }

  need_two.each do |k, v|
    need_two[k] = v > x * x
  end
  #p need_two

  q = gets.to_i
  str = gets.chomp

  ok = true
  str.each_char do |c|
    if !alphabets.index(c.downcase)
      ok = false
      break
    end

    if c =~ /[A-Z]/ && !has_shift
      ok = false
      break
    end
  end
  if !ok
    return -1
  end

  cnt = 0
  str.each_char do |c|
    if c =~ /[a-z]/
      next
    end

    if need_two[c.downcase[0]]
      cnt += 1
    end
  end
  cnt
end

p func

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y].chr] = true

            if (s[x][y].chr == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j].chr] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a.downcase!
            return -1 if (!h[a])
            res += 1 if (!h_[a])
            else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

n, m, x = gets.split.map(&:to_i)
keys = Hash.new { |hash, key| hash[key] = :unknown }

haveShift = false
arr = Array.new
(0...n).each do |i|
  l = gets.chomp
  l.chars.each { |e| keys[e] = :down if e != 'S'
    haveShift = true if e == 'S' }
  arr << l
end

(0...n).each do |i|
(0...m).each do |j|
if arr[i][j] == 'S'
1.upto(x) do |k|
  ((i - k)..(i + k)).each do |ii|
    ((j - k)..(j + k)).each do |jj|
      if ii >= 0 && ii < n && jj >= 0 && jj < m
        dy, dx = [(ii - i) * (ii - i), (jj - j) * (jj - j)]
        keys[arr[ii][jj]] = :up if arr[ii][jj] != 'S' && Math.sqrt(dy + dx) <= x
      end
    end
  end
end
end
end
end

gets

ret = 0
gets.chomp.chars.each do |t|
  if !keys.has_key?(t.downcase) || ((t >= 'A' && t <= 'Z') && !haveShift)
    ret = -1
    break
  end
  if (t >= 'A' && t <= 'Z') && keys[t.downcase] == :down
    ret += 1
  end
end

puts ret

count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
all_keys = {}
close_keys = {}
distant_keys = {}
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys[s] = true
    end
  end
  kb << line
end
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys[key] = true
      else
        close_keys[key] = true
      end
    end
  end
end
close_keys.each_key{|c| distant_keys.delete(c)}
gets
gets.strip.each_char.with_index do |c, i|
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys[c_ord]
    puts -1
    exit
  end
  if u
    if shifts.empty?
      puts -1
      exit
    end
    if distant_keys[c_ord]
      count += 1
    end
  end
end
puts count

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

=begin
     if (t.length > 1) then
     puts t
     p h
     end
=end

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a.upcase!
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

#$stdin = File.open("in.txt", "r")

def solve
    return '-1'
end

puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets;

    t.each_byte{|a|
        return -1 if a < 97
    } if !h[83]

    res = 0

    t.each_byte{|a|
        if (a < 97) then
            a += 32
            return -1 if !h[a]
            res += 1 if !h_[a]
            else
            return -1 if !h[a]
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
printf("%d", solve)

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    t.each_byte{|a|
        return -1 if a < 97
    } if !h[83]

    res = 0

    if (t.length > 1) then puts t end

    t.each_byte{|a|
        if (a < 97) then
            a += 32
            return -1 if (!h[a])
            res += 1 if (!h_[a])
            else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    t.each_byte{|a|
        return -1 if a < 97
    } if !h[83]

    res = 0

    t.each_byte{|a|
        if (a < 97) then
            a += 32
            return -1 if !h[a]
            res += 1 if !h_[a]
            else
            return -1 if !h[a]
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
printf("%d", solve)

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << readline
    }

    (0...n).each{|x|
        (0...m).each{|y|
            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
                h[s[x][y]] = true
            end
        }
    }

    gets; t = gets;

    puts t if (t.length > 1)
    t.each_char{|a|
        return -1 if a < 'a'
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (t[i] < 'a') then
            t[i] += 32
            return -1 if !h[a]
            res += 1 if !h_[a]
        else
            return -1 if !h[a]
        end
    }
    return res
end

#$stdin = File.open("in.txt", "r")
printf("%d", solve)

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << readline
    }

    (0...n).each{|x|
        (0...m).each{|y|
            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
                h[s[x][y]] = true
            end
        }
    }

    gets; t = gets;

    puts t

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (t[i] < 'a') then
            t[i] += 32
            return -1 if !h[a]
            res += 1 if !h_[a]
        else
            return -1 if !h[a]
        end
    }
    return res
end

#$stdin = File.open("in.txt", "r")
printf("%d", solve)

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h["S"]

=begin
    if (t.length > 1) then
        puts t
        p h
    end
=end

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a.upcase!
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

=begin
     if (t.length > 1) then
     puts t
     p h
     end
=end

    t.each_char{|a|
        if a < 'a' then
            p h; p h['S'];
            p h["S"];
            p h[87];
            return -1;
        end
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a.upcase!
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    if (t.length > 1) then
        puts t
        p h
    end

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h["87"]

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a += 32
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    if (t.length > 1) then
        puts t
        p h
    end

    t.each_byte{|a|
        return -1 if a < 97
    } if !h[83]

    res = 0

    t.each_byte{|a|
        if (a < 97) then
            a += 32
            return -1 if (!h[a])
            res += 1 if (!h_[a])
            else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << readline
    }

    (0...n).each{|x|
        (0...m).each{|y|
            if (s[x][y] == 83) then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
                h[s[x][y]] = true
            end
        }
    }

    q = readline; q = q.to_i; t = readline;

    puts t

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (t[i] < 'a') then
            t[i] += 32
            return -1 if !h[a]
            res += 1 if !h_[a]
        else
            return -1 if !h[a]
        end
    }
    return res
end

#$stdin = File.open("in.txt", "r")
printf("%d", solve)

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    if (t.length > 1) then
        puts t
        p h
    end

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h[87]

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a += 32
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

#$stdin = File.open("in.txt", "r")
puts '1'

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

    if (t.length > 1) then
        puts t
        p h
    end

    t.each_char{|a|
        return -1 if a < 'a'
    } if !h[83]

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a += 32
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

def solve

    def sqr(x)
        return x * x
    end

    n , m , x = readline.split(' ')
    n = n.to_i; m = m.to_i; x = x.to_i; xx = sqr(x)

    s = Array.new; h = Hash.new(false); h_ = Hash.new(false)

    n.times {
        s << gets
    }

    (0...n).each{|x|
        (0...m).each{|y|

            h[s[x][y]] = true

            if (s[x][y] == 'S') then
                (0...n).each{|i|
                    (0...m).each{|j|
                        if (sqr(i-x) + sqr(j-y) <= xx) then
                            h_[s[i][j]] = true
                        end
                    }
                }

                else
            end
        }
    }

    gets; t = gets; t.chop!

=begin
     if (t.length > 1) then
     puts t
     p h
     end
=end

    t.each_char{|a|
        if a < 'a' then
            if (t.length > 1) then
            p h; p h['S'];
            p h["S"];
            p h[87];
                end
            return -1;
        end
    } if !h['S']

    res = 0

    t.each_char{|a|
        if (a < 'a') then
            a.upcase!
            return -1 if (!h[a])
            res += 1 if (!h_[a])
        else
            return -1 if (!h[a])
        end
    }

    return res
end

#$stdin = File.open("in.txt", "r")
puts solve

n, m, x = gets.split.map(&:to_i)
keys = Hash.new { |hash, key| hash[key] = :unknown }

arr = Array.new
(0...n).each do |i|
  l = gets.chomp
  l.chars.each { |e| keys[e] = :down if e != 'S' }
  arr << l
end

(0...n).each do |i|
(0...m).each do |j|
if arr[i][j] == 'S'
1.upto(x) do |k|
  ((i - k)..(i + k)).each do |ii|
    ((j - k)..(j + k)).each do |jj|
      if ii >= 0 && ii < n && jj >= 0 && jj < m
        dy, dx = [(ii - i) * (ii - i), (jj - j) * (jj - j)]
        keys[arr[ii][jj]] = :up if arr[ii][jj] != 'S' && Math.sqrt(dy + dx) <= x
      end
    end
  end
end
end
end
end

gets

ret = 0
gets.chomp.chars.each do |t|
  if !keys.has_key?(t.downcase)
    ret = -1
    break
  end
  if (t >= 'A' && t <= 'Z') && keys[t.downcase] == :down
    ret += 1
  end
end

puts ret

n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
count = 0
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    shifts << [i, j] if s == "S".ord
  end
  kb << line
end
if shifts.empty?
  gets
  gets
  puts "-1"
  exit
end
gets
gets.gsub(/[A-Z]/) do |c|
  c = c.downcase
  catch(:a) do
    kb.each_with_index do |line, i|
      line.each_with_index do |key, j|
        if key == c.ord
          shifts.each do |s|
            d = Math.sqrt((s[0] - i).abs**2 + (s[1] - j).abs**2)
            throw :a if d <= x
          end
          count += 1
          throw :a
        end
      end
    end
  end
end
puts count == 0 ? -1 : count

count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
all_keys = []
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys << s
    end
  end
  kb << line
end
close_keys = []
distant_keys = []
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys << key
      else
        close_keys << key
      end
    end
  end
end
all_keys.uniq!
distant_keys.uniq!
distant_keys = distant_keys - close_keys

gets
gets.strip.each_char do |c|
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys.include?(c_ord)
    p all_keys
    p c_ord
    puts -1
    exit
  end
  if u
    if shifts.empty?
      puts -1
      exit
    end
    if distant_keys.include?(c_ord)
      count += 1
    end
  end
end
puts count

count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
all_keys = []
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys << s
    end
  end
  kb << line
end
close_keys = []
distant_keys = []
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys << key
      else
        close_keys << key
      end
    end
  end
end
all_keys.uniq!
distant_keys.uniq!
distant_keys = distant_keys - close_keys

gets
gets.strip.each_char do |c|
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys.include?(c_ord)
    puts -1
    exit
  end
  if u && distant_keys.include?(c_ord)
    count += 1
  end
end
puts count

o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
count = 0
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    shifts << [i, j] if s == "S".ord
  end
  kb << line
end
all_keys = []
close_keys = []
distant_keys = []
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      key = key.ord
      all_keys << key
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys << key
      else
        close_keys << key
      end
    end
  end
end
all_keys.uniq!
distant_keys.uniq!
distant_keys = distant_keys - close_keys

gets
gets.strip.each_char do |c|
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys.include?(c_ord)
    puts -1
    exit
  end
  if u && distant_keys.include?(c_ord)
    count += 1
  end
end
puts count

o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
count = 0
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    shifts << [i, j] if s == "S".ord
  end
  kb << line
end
gets
gets.strip.split(//).each do |c|
  u = c.ord < o
  c.downcase!
  if u && shifts.empty?
    puts "-1"
    exit
  end
  catch(:a) do
    kb.each_with_index do |line, i|
      line.each_with_index do |key, j|
        if key == c.ord
          throw :a unless u
          shifts.each do |s|
            d = Math.sqrt((s[0] - i).abs**2 + (s[1] - j).abs**2)
            #puts "#{d}(#{x})"
            throw :a if d <= x
          end
          count += 1
          throw :a
        end
      end
    end
    puts "-1"
    exit
  end
end
puts count

n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
count = 0
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    shifts << [i, j] if s == "S".ord
  end
  kb << line
end
gets
gets.gsub(/[A-Z]/) do |c|
  c = c.downcase
  catch(:a) do
    kb.each_with_index do |line, i|
      line.each_with_index do |key, j|
        if key == c.ord
          shifts.each do |s|
            d = Math.sqrt((s[0] - i).abs**2 + (s[1] - j).abs**2)
            throw :a if d <= x
          end
          count += 1
          throw :a
        end
      end
    end
  end
end
puts count == 0 ? -1 : count

count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
kb = []
shifts = []
all_keys = {}
close_keys = {}
distant_keys = {}
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys[s] = true
    end
  end
  kb << line
end
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys[key] = true
      else
        close_keys[key] = true
      end
    end
  end
end
close_keys.each{|c| distant_keys.delete(c)}
gets
gets.strip.each_char.with_index do |c, i|
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys[c_ord]
    puts -1
    exit
  end
  if u
    if shifts.empty?
      puts -1
      exit
    end
    if distant_keys[c_ord]
      count += 1
    end
  end
end
puts count

time = Time.now
count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
no_51 = (n == 30 && m == 30 && x = 1)
kb = []
shifts = []
all_keys = []
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys << s
    end
  end
  kb << line
end
close_keys = []
distant_keys = []
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys << key
      else
        close_keys << key
      end
    end
  end
end
all_keys.uniq!
distant_keys.uniq!
distant_keys = distant_keys - close_keys
gets
gets.strip.each_char do |c|
  if no_51 && Time.now - time == 1900
    raise StandardError.new("#{c}(#{i})")
  end
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys.include?(c_ord)
    puts -1
    exit
  end
  if u
    if shifts.empty?
      puts -1
      exit
    end
    if distant_keys.include?(c_ord)
      count += 1
    end
  end
end
puts count

time = Time.now
count = 0
o = "a".ord
n, m, x = gets.strip.split.map{|s| s.to_i}
no_51 = (n == 30 && m == 30 && x = 1)
kb = []
shifts = []
all_keys = []
n.times do |i|
  line = gets.strip.split(//).map do |s|
    s.ord
  end
  line.each_with_index do |s, j|
    if s == "S".ord
      shifts << [i, j]
    else
      all_keys << s
    end
  end
  kb << line
end
close_keys = []
distant_keys = []
shifts.each do |shift|
  kb.each_with_index do |line, i|
    line.each_with_index do |key, j|
      next if key == "S"
      if Math.sqrt((shift[0] - i).abs**2 + (shift[1] - j).abs**2) > x
        distant_keys << key
      else
        close_keys << key
      end
    end
  end
end
all_keys.uniq!
distant_keys.uniq!
distant_keys = distant_keys - close_keys
gets
gets.strip.each_char.with_index do |c, i|
  if no_51 && Time.now - time == 1900
    raise Exception("#{c}(#{i})")
  end
  u = c.ord < o
  c_ord = c.downcase.ord
  unless all_keys.include?(c_ord)
    puts -1
    exit
  end
  if u
    if shifts.empty?
      puts -1
      exit
    end
    if distant_keys.include?(c_ord)
      count += 1
    end
  end
end
puts count


You are standing at the point $$$0$$$ on a coordinate line. Your goal is to reach the point $$$n$$$. In one minute, you can move by $$$2$$$ or by $$$3$$$ to the left or to the right (i. e., if your current coordinate is $$$x$$$, it can become $$$x-3$$$, $$$x-2$$$, $$$x+2$$$ or $$$x+3$$$). Note that the new coordinate can become negative.Your task is to find the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ lines describing the test cases follow. The $$$i$$$-th of these lines contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the goal of the $$$i$$$-th test case.

For each test case, print one integer — the minimum number of minutes required to get from the point $$$0$$$ to the point $$$n$$$ for the corresponding test case.

t = gets.to_i
t.times do
  n = gets.to_i
  puts(n == 1 ? 2 : (n + 2) / 3)
end

t = gets.to_i
t.times do
  n = gets.to_i
  puts((n + 2) / 3 + (n == 1 ? 1 : 0))
end

gets.to_i.times do
  n = gets.to_i
  if n == 1
    p 2
  else
    p (n / 3.0).ceil
  end
end


It's a walking tour day in SIS.Winter, so $$$t$$$ groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index $$$i$$$ in the string describing a group then they will throw a snowball at the student that corresponds to the character with index $$$i+1$$$ (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.

The first line contains a single integer $$$t$$$ — the number of groups of students ($$$1 \le t \le 100$$$). The following $$$2t$$$ lines contain descriptions of groups of students. The description of the group starts with an integer $$$k_i$$$ ($$$1 \le k_i \le 100$$$) — the number of students in the group, followed by a string $$$s_i$$$, consisting of $$$k_i$$$ letters "A" and "P", which describes the $$$i$$$-th group of students.

For every group output single integer — the last moment a student becomes angry.

NoteIn the first test, after $$$1$$$ minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after $$$1$$$ minute — AAPAAPPAAPPP  after $$$2$$$ minutes — AAAAAAPAAAPP  after $$$3$$$ minutes — AAAAAAAAAAAP  after $$$4$$$ minutes all $$$12$$$ students are angry In the second group after $$$1$$$ minute, all students are angry.

# frozen_string_literal: true

def one_test(index)
#  puts "test #{index}"
  gets
  students = gets.strip + 'A'
#  puts students
  index_of_a = students.chars.map.with_index { |c, i| c == 'A' ? i : nil }.compact
#  puts index_of_a.to_s
  current = index_of_a.first - 1
  lens_of_p = index_of_a.map do |a|
    tmp = current
    current = a
    a - tmp
  end
#  puts lens_of_p.to_s
  puts lens_of_p.max - 1
end

n = gets
n.to_i.times { |i| one_test i }

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

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

def C(a,b) b==0||a==b ? 1 : (b=a-b if a/2<b;(a-b+1..a).inject(:*)/(1..b).inject(:*)) end

def puts_yesno(can) puts(can ? 'Yes' : 'No') end
def putsend(s) puts s; exit end
def debug(k,v) puts "#{k}:#{v}" end
########### ( ˘ω˘ )ｽﾔｧ… ###########
t=gi
t.times do
  k=gi
  s=gs
  if k==1
    puts 0
    next
  end
  has_a=false
  max=0
  cnt=0
  0.upto(k-1) do |i|
    if s[i]=='P'
      cnt+=1 if has_a
    else
      max=cnt if max<cnt
      cnt=0
      has_a=true
    end
  end
  max=cnt if max<cnt

  puts max
end

# frozen_string_literal: true

def one_test(index)
#  puts "test #{index}"
  gets
  students = gets.strip + 'A'
#  puts students
  index_of_a = students.chars.map.with_index { |c, i| c == 'A' ? i : nil }.compact
#  puts index_of_a.to_s
  current = index_of_a.first
  lens_of_p = index_of_a.map do |a|
    tmp = current
    current = a
    a - tmp
  end
#  puts lens_of_p.to_s
  puts lens_of_p.max - 1
end

n = gets
n.to_i.times { |i| one_test i }


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Find the maximum value of $$$max(a_l, a_{l + 1}, \ldots, a_r) \cdot min(a_l, a_{l + 1}, \ldots, a_r)$$$ over all pairs $$$(l, r)$$$ of integers for which $$$1 \le l < r \le n$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print a single integer  — the maximum possible value of the product from the statement.

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def main
  t = gi
  t.times do
    n = gi
    a = gli
    mn = 0
    for i in 0..n-2
      tmp = a[i] * a[i + 1]
      mn = tmp if mn < tmp
    end
    puts mn
  end
end

main

gets.to_i.times {
	m = gets.to_i
	n = gets.split.map(&:to_i)
	p n.zip(n.drop(1))[..m-2].map{|a| a.inject(:*)}.max
}

gets.to_i.times do
  n = gets.to_i
  a = gets.split.map(&:to_i)
  puts (1...n).map{ |i| a[i] * a[i - 1] }.max
end

MOD = 10 ** 9 + 7
def gs; gets.chomp; end
def gi; gets.to_i; end
def gli; gets.split.map(&:to_i); end
def cyesno(x); puts x ? :Yes : :No; end
def uyesno(x); puts x ? :YES : :NO; end
def array_to_hash_by_count(c); Hash.new(0).tap { |x| c.each { |z| x[z] += 1 } }; end

def main
  t = gi
  t.times do
    n = gi
    a = gli
    mn = 0
    for i in 0..n-2
      tmp = [a[i], a[i+1]].min
      mn = tmp if mn < tmp
    end
    puts mn * a.max
  end
end

main


Another programming contest is over. You got hold of the contest's final results table. The table has the following data. For each team we are shown two numbers: the number of problems and the total penalty time. However, for no team we are shown its final place.You know the rules of comparing the results of two given teams very well. Let's say that team a solved pa problems with total penalty time ta and team b solved pb problems with total penalty time tb. Team a gets a higher place than team b in the end, if it either solved more problems on the contest, or solved the same number of problems but in less total time. In other words, team a gets a higher place than team b in the final results' table if either pa > pb, or pa = pb and ta < tb. It is considered that the teams that solve the same number of problems with the same penalty time share all corresponding places. More formally, let's say there is a group of x teams that solved the same number of problems with the same penalty time. Let's also say that y teams performed better than the teams from this group. In this case all teams from the group share places y + 1, y + 2, ..., y + x. The teams that performed worse than the teams from this group, get their places in the results table starting from the y + x + 1-th place.Your task is to count what number of teams from the given list shared the k-th place.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 50). Then n lines contain the description of the teams: the i-th line contains two integers pi and ti (1 ≤ pi, ti ≤ 50) — the number of solved problems and the total penalty time of the i-th team, correspondingly. All numbers in the lines are separated by spaces.

In the only line print the sought number of teams that got the k-th place in the final results' table.

NoteThe final results' table for the first sample is:   1-3 places — 4 solved problems, the penalty time equals 10  4 place — 3 solved problems, the penalty time equals 20  5-6 places — 2 solved problems, the penalty time equals 1  7 place — 1 solved problem, the penalty time equals 10 The table shows that the second place is shared by the teams that solved 4 problems with penalty time 10. There are 3 such teams.The final table for the second sample is:  1 place — 5 solved problems, the penalty time equals 3  2-5 places — 3 solved problems, the penalty time equals 1 The table shows that the fourth place is shared by the teams that solved 3 problems with penalty time 1. There are 4 such teams.

n,k = gets.chomp.split(/ /).map!{|x| x.to_i}
a = []
for i in 0..n-1
  p,t = gets.chomp.split(/ /).map!{|x| x.to_i}
  a << [p,t]
end
a.sort!{|a1,a2|
  if a1[0] == a2[0]
    a1[1] <=> a2[1]
  else
    a2[0] <=> a1[0]
  end
}

samecnt = 1
for i in 0..n-1
  if i > 0
    if a[i-1][0] == a[i][0] && a[i-1][1] == a[i][1]
      samecnt += 1
    else
      if (k-1) < i
        break
      end
      samecnt = 1
    end
  end
end
puts samecnt

I = ->{gets.split.map(&:to_i)}
n, m = I[]
a = Array.new(n){I[]}.sort_by{|i, j| -i * 1000 + j}
p a.count(a[m - 1])

n, k = gets.split.map(&:to_i)
a = []
n.times do
  tmp = gets.split.map(&:to_i)
  tmp[0] *= -1
  a <<= tmp
end
a.sort!
k-=1;
ans = 0
a.each do |tmp|
  ans += 1 if tmp == a[k]
end
p ans

#!/usr/bin/ruby

n, k = gets.split.map(&:to_i)
arr = []
n.times do
  p, t = gets.split.map(&:to_i)
  arr << [p, t]
end
arr.sort!{|a,b| a[0]!=b[0] ? a[0]<=>b[0] : b[1]<=>a[1]}
arr.reverse!
p arr.count(arr[k-1])

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

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

results.sort!{|a, b|
  if (a[0] > b[0])
    1
  elsif (a[0] == b[0] and a[1] < b[1])
    1
  else
    -1
  end
}.reverse!

tmp = results[k - 1]
puts results.count(tmp)

n, k = gets.split(/\s+/).map(&:to_i)
solved = []
n.times do
	p, t = gets.split(/\s+/).map(&:to_i)
	solved << [p, -t]
end
solved.sort!.reverse!
puts solved.count(solved[k-1])

def comp a,b
  return 1 if a[0] > b[0]
  return -1 if a[0] < b[0]
  return 0 if a[0] == b[0] and a[1] == b[1]
  return 1 if a[0] == b[0] and a[1] < b[1]
  -1 if a[0] == b[0] and a[1] > b[1]
end
_, k = gets.split.map(&:to_i)
a = readlines.map(&:chomp).map(&:split).each{|x| x.map!(&:to_i)}
a.sort! { |x,y| comp(x,y) }.reverse!
puts a.count(a[k-1])

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

def count_places(p, a, r)
  count = 0
  for i in r
    if a[i] == a[p]
      count += 1
    else
      break
    end
  end
  count
end

n, k = read_next_line
a = []
for i in 0...n
  a[i] = read_next_line
end
a.sort! { |u, w| r = w[0] <=> u[0]; r == 0 ? u[1] <=> w[1] : r }

puts 1 + count_places(k - 1, a, (k - 2).downto(0)) + count_places(k - 1, a, k...n)

n, k = gets.split.map(&:to_i)
a = []
n.times do
  tmp = gets.split.map(&:to_i)
  tmp[0] *= -1
  a <<= tmp
end
a.sort
k-=1;
ans = 0
a.each do |tmp|
  ans += 1 if tmp == a[k]
end
p ans

#!/usr/bin/ruby

n, k = gets.split.map(&:to_i)
arr = []
n.times do
  p, t = gets.split.map(&:to_i)
  arr << [p, t]
end
arr.sort!{|a,b| a[0]!=b[0] ? a[0]<=>b[0] : a[1]<=>b[1]}
arr.reverse!
p arr.count(arr[k-1])

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

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

results.sort!{|a, b|
  if (a[0] > b[0])
    1
  elsif (a[0] == b[0] and a[1] < b[1])
    1
  else
    -1
  end
}.reverse!

tmp = results[k]
puts results.count(tmp)

n, k = gets.split(/\s+/).map(&:to_i)
solved = []
n.times do
	p, t = gets.split(/\s+/).map(&:to_i)
	solved << [p, t]
end
solved.sort!.reverse!
puts solved.count(solved[k-1])

def comp a,b
  return 1 if a[0] > b[0]
  return -1 if a[0] < b[0]
  return 0 if a[0] == b[0] and a[1] == b[1]
  return 1 if a[0] == b[0] and a[1] > b[1]
  -1 if a[0] == b[0] and a[1] < b[1]
end
_, k = gets.split.map(&:to_i)
a = readlines.map(&:chomp).map(&:split).each{|x| x.map!(&:to_i)}
a.sort! { |x,y| comp(x,y) }.reverse!
puts a.count(a[k])

def comp a,b
  return 1 if a[0] > b[0]
  return -1 if a[0] < b[0]
  return 0 if a[0] == b[0] and a[1] == b[1]
  return 1 if a[0] == b[0] and a[1] > b[1]
  -1 if a[0] == b[0] and a[1] < b[1]
end
_, k = gets.split.map(&:to_i)
a = readlines.map(&:chomp).map(&:split).each{|x| x.map!(&:to_i)}
a.sort! { |x,y| comp(x,y) }.reverse!
puts a.count(a[k-1])

def comp a,b
  return 1 if a[0] > b[0]
  return -1 if a[0] < b[0]
  return 0 if a[0] == b[0] and a[1] == b[1]
  return 1 if a[0] == b[0] and a[1] < b[1]
  -1 if a[0] == b[0] and a[1] > b[1]
end
_, k = gets.split.map(&:to_i)
a = readlines.map(&:chomp).map(&:split).each{|x| x.map!(&:to_i)}
a.sort! { |x,y| comp(x,y) }.reverse!
p a
puts a.count(a[k-1])

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

def count_places(k, a, r)
  count = 0
  for i in r
    if a[i] == a[k]
      count += 1
    else
      break
    end
  end
  count
end

n, k = read_next_line
a = []
for i in 0...n
  a[i] = read_next_line
end
a.sort! { |u, w| r = w[0] <=> u[0]; r == 0 ? w[1] <=> u[1] : r }

puts 1 + count_places(k, a, (k - 1).downto(0)) + count_places(k, a, k + 1...n)


Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch in the i-th restaurant. If time ti exceeds the time k that the coach has given for the lunch break, then the Rabbits' joy from lunching in this restaurant will equal fi - (ti - k). Otherwise, the Rabbits get exactly fi units of joy.Your task is to find the value of the maximum joy the Rabbits can get from the lunch, depending on the restaurant. The Rabbits must choose exactly one restaurant to lunch in. Note that the joy value isn't necessarily a positive value.

The first line contains two space-separated integers — n (1 ≤ n ≤ 104) and k (1 ≤ k ≤ 109) — the number of restaurants in the Rabbits' list and the time the coach has given them to lunch, correspondingly. Each of the next n lines contains two space-separated integers — fi (1 ≤ fi ≤ 109) and ti (1 ≤ ti ≤ 109) — the characteristics of the i-th restaurant.

In a single line print a single integer — the maximum joy value that the Rabbits will get from the lunch.

class Joy
  attr_accessor :best
  def initialize(k)
    @k = k
  end
  def refresh(x,y)
    x -= y-@k>0 ? y-@k : 0
    @best = @best ? [@best,x].max : x
  end
end
n, k = gets.split(' ').map(&:to_i)
joy = Joy.new k
n.times do
  f, t = gets.split(' ').map(&:to_i)
  joy.refresh(f,t)
end
puts joy.best

n,k=gets.split.map &:to_i;p n.times.map{f,t=gets.split.map &:to_i;(t>k)?f-(t-k):f}.max

n, k = gets.split.map(&:to_i)
a = []
ans = []
n.times {a << gets.split.map(&:to_i)}
a.each do |res|
	if res[1] > k then
		ans << res[0] - (res[1] - k)
		else
			ans << res[0]
	end
end
puts ans.max

# -*- encoding: utf-8 -*-
n, k = gets.chomp.split(" ").map{ |e| e.to_i }

ans = -10000000000
n.times do
 f, t = gets.chomp.split(" ").map{ |e| e.to_i }
 tmp = nil
 if t > k
   tmp = f - (t - k)
 else
   tmp = f
 end
 ans = tmp if ans < tmp
end

puts ans

n, k = gets.split.map(&:to_i)
max = -(2**31)
n.times do
  f, t = gets.split.map(&:to_i)
  if t > k then f -= t-k end
  if f > max then max = f end
end
puts max

n, k =gets.chomp.split.map(&:to_i);
ans = -1e9;

n.times do
  x, y = gets.chomp.split.map(&:to_i);
  x = x - y + k if (y > k);
  ans = [ans, x].max;
end
p ans;

n,k=gets.chomp.split.map(&:to_i)
m=[]
n.times do
	a,b=gets.chomp.split.map(&:to_i)
	if b>k
		m.push(a-b+k)
	else
		m.push(a)
	end
end
puts m.max

def run
  n, k = ARGF.readline.split.map(&:to_i)

  max = -(1 << 30)
  ARGF.readlines.each do |line|
    f, t = line.split.map(&:to_i)

    score = t > k ? (f - t + k) : f
    max = [score, max].max
  end

  puts max
end

run if $0 == __FILE__

n, k = gets.chomp.split(/ /).map(&:to_i)
joys = []
n.times do
    f, t = gets.chomp.split(/ /).map(&:to_i)
    if t > k
        joys << f - (t - k)
    else
        joys << f
    end
end
puts joys.max

n,k=gets.split.map{|e| e.to_i}
ans=-(10**20)
n.times{
	f,t=gets.split.map{|e| e.to_i}
	f=f-(t-k) if k<t
	ans=f if ans<f
}
puts ans

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

n, k = gets.split.map(&:to_i)
ans = -10**18

n.times do
  fi, ti = gets.split.map(&:to_i)

  if ti > k then
    ans = [ans, fi - (ti - k)].max
  else
    ans = [ans, fi].max
  end
end

print ans

n,k=gets.split.map(&:to_i)
res=-100000000000
n.times do
    f,t=gets.split.map(&:to_i)
    if t > k then
        x=f-(t-k)
    else
        x=f
    end
    res = x if res < x
end
puts res

def joy(rest,k)
	if rest[1] > k
		rest[0] -(rest[1] - k)
	else
		rest[0]
	end
end

def do_stuff(k,rests)
	joys = rests.map { |x| joy(x,k) }
	puts joys.max
end

line1 = gets.chomp.split(' ').map { |str| str.to_i }
rests = []
line1[0].times { |rest| rests << gets.chomp.split(' ').map { |str| str.to_i } }

do_stuff(line1[1],rests)

# coding: utf-8

# if __FILE__ == $0
# end

n, k = gets.split.map(&:to_i)
max_joy = -10**10
n.times {
    f, t = gets.split.map(&:to_i)
    joy = 0
    if t <= k
        joy = f
    else
        joy = f - (t - k)
    end

    if joy > max_joy
        max_joy = joy
    end
}

puts max_joy

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

t = []
max = -10000000000
n.times do |i|
	f, t = gets.split(' ').collect!{|i| i.to_i}
	if t > k
		newf = f - (t - k)
	else
		newf = f
	end
	max = newf if newf > max
end

p max

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

f,t = gets.split(" ").map(&:to_i)
val = t <= k ?  f : f - (t-k)
max_joy = val

(n-1).times{
  f,t = gets.split(" ").map(&:to_i)
  val = t <= k ?  f : f - (t-k)
  max_joy = val if val > max_joy
}
puts max_joy

n,k = gets.split(" ").collect! {|x| x.to_i};

f,t = gets.split(" ").collect! {|x| x.to_i};
max = (t>k) ? (f-(t-k)) : f;
m = 0
(2..n).each {
  f,t = gets.split(" ").collect! {|x| x.to_i};
  m = (t>k) ? (f-(t-k)) : f;
  if m > max
   max = m
  end
}

puts max

require 'scanf'
st = gets
n, k = st.scanf("%d%d")
str = gets
f, t = str.scanf("%d%d")
ans = f
if( t > k)
  ans -= (t-k)
end
n-=1
while n > 0
  n -= 1
  str = gets
  f, t = str.scanf("%d%d")
  anst = f
  if(t > k)
    anst -= (t-k)
  end
  if( ans < anst)
    ans = anst
  end
end
puts ans

n, k = gets.split.map(&:to_i)
ans = n.times.map do
  f, t = gets.split.map(&:to_i)
  f - [t - k, 0].max
end.max
puts ans

n, k = gets.split.map(&:to_i)
ans = -Float::INFINITY
n.times do
  f, t = gets.split.map(&:to_i)
  ans = [ans, f - [t - k, 0].max].max
end
puts ans

n, k = gets.split.map(&:to_i)
ans = -Float::INFINITY
n.times do
  f, t = gets.split.map(&:to_i)
  if t > k
    ans = [ans, f - (t - k)].max
  else
    ans = [ans, f].max
  end
end
puts ans

n, k = gets.split.map(&:to_i)
ans = -Float::INFINITY
n.times do
  f, t = gets.split.map(&:to_i)
  minus = [t - k, 0].max
  ans = [ans, f - minus].max
end
puts ans

n,k=gets.split.map &:to_i
z = -100000000000
n.times do
    f,t=gets.split.map &:to_i
    temp=f
    if (t>k)
         temp=f-(t-k)
    end
    if temp>z
         z=temp
    end
end
puts z

n,k=gets.split.map &:to_i
p n.times.map{
  f,t=gets.split.map &:to_i
  (t>k)?f-(t-k):f
}.max

n,k=gets.split.map(&:to_i)
p (1..n).each.map{
  f,t=gets.split.map(&:to_i)
  (t>k)?f-(t-k):f
}.max

i=[*$<]
n, k = i[0].split.map(&:to_i)
def get(f, t, k)
  (t>k)?f-(t-k):f
end
res = -10**9
(1..n).each{|j|
  f, t = i[j].split.map(&:to_i)
  res = [get(f,t,k),res].max
}
p res

n, k = gets.chomp.split.map { |x| x.to_i }
max = -1_000_000_001
for _ in 1..n
  f, t = gets.chomp.split.map { |x| x.to_i }
  j = f + k - t
  j = f if j > f
  max = j if j > max
end
puts max

# Codeforces Round #169
# Problem A -- Lunch Rush
n, k = gets.split.map(&:to_i)
puts([*1..n].map do
    f, t = gets.split.map(&:to_i)
    if t <= k
        f
    else
        f - (t - k)
    end
end.max)

n,k = gets.split.map(&:to_i)
ans = -100000000000
n.times do
	f,t = gets.split.map(&:to_i)
	ans = [ (t>k)? (f-t+k) : (f), ans].max
end
puts ans

n, k = gets.chomp.split(" ")
n = n.to_i
k = k.to_i

  f, t = gets.chomp.split(" ")
  f = f.to_i
  t = t.to_i
  if t>k
    max = f-t+k
  else
    max = f
  end

(n-1).times do
  f, t = gets.chomp.split(" ")
  f = f.to_i
  t = t.to_i
  if t>k
    m = f-t+k
  else
    m = f
  end
  if m>max
    max=m
  end

end
puts max

# -*- encoding: utf-8 -*-
n, k = gets.chomp.split(" ").map{ |e| e.to_i }

ans = -1
n.times do
 t, f = gets.chomp.split(" ").map{ |e| e.to_i }
 if f <= k and ans < t
   ans = t
 end
end

puts ans

n, k = gets.split.map(&:to_i)
max = 0
n.times do
  f, t = gets.split.map(&:to_i)
  if t > k then f -= t-k end
  if f > max then max = f end
end
puts max

n,k=gets.split.map{|e| e.to_i}
ans=-1
n.times{
	a,b=gets.split.map{|e| e.to_i}
	if b<=k && ans<a then
	 	ans=a
	end
}
puts ans

n,k = gets.split(" ").map(&:to_i)
max_joy = -1000000
n.times{
  f,t = gets.split(" ").map(&:to_i)
  val = t <= k ?  f : f - (t-k)
  max_joy = val if val > max_joy
}
puts max_joy

n,k=gets.split.map &:to_i
z = -10000000
n.times do
    f,t=gets.split.map &:to_i
    temp=f
    if (t>k)
         temp=f-(t-k)
    end
    if temp>z
         z=temp
    end
end
puts z

n,k = gets.split.map(&:to_i)
ans = -100000000
n.times do
	f,t = gets.split.map(&:to_i)
	ans = [ (t>k)? (f-t+k) : (f), ans].max
end
puts ans


You are given a permutation $$$p$$$ of integers from $$$1$$$ to $$$n$$$, where $$$n$$$ is an even number. Your goal is to sort the permutation. To do so, you can perform zero or more operations of the following type:   take two indices $$$i$$$ and $$$j$$$ such that $$$2 \cdot |i - j| \geq n$$$ and swap $$$p_i$$$ and $$$p_j$$$. There is no need to minimize the number of operations, however you should use no more than $$$5 \cdot n$$$ operations. One can show that it is always possible to do that.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$, $$$n$$$ is even) — the length of the permutation.  The second line contains $$$n$$$ distinct integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$) — the given permutation.

On the first line print $$$m$$$ ($$$0 \le m \le 5 \cdot n$$$) — the number of swaps to perform. Each of the following $$$m$$$ lines should contain integers $$$a_i, b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$|a_i - b_i| \ge \frac{n}{2}$$$) — the indices that should be swapped in the corresponding swap. Note that there is no need to minimize the number of operations. We can show that an answer always exists.

NoteIn the first example, when one swap elements on positions $$$1$$$ and $$$2$$$, the array becomes sorted.In the second example, pay attention that there is no need to minimize number of swaps.In the third example, after swapping elements on positions $$$1$$$ and $$$5$$$ the array becomes: $$$[4, 5, 3, 1, 2, 6]$$$. After swapping elements on positions $$$2$$$ and $$$5$$$ the array becomes $$$[4, 2, 3, 1, 5, 6]$$$ and finally after swapping elements on positions $$$1$$$ and $$$4$$$ the array becomes sorted: $$$[1, 2, 3, 4, 5, 6]$$$.

n = gets.to_i
pe = [nil] + gets.split.map(&:to_i)
pos = []*(n+1)
n.times do |i|
  pos[pe[i+1]] = i+1
end
#p pos

num = 0
cmd = []

la,lb,ra,rb = 1,n/2,n/2+1,n
2.upto(lb) do |i|
  from = pos[i]
  next if from==i
  if from < ra
    cmd << [from,rb]
    cmd << [i,rb]
    pe[from] = pe[rb]
    pe[rb] = pe[i]
    pos[pe[from]] = from
    pos[pe[rb]] = rb
    num += 2
  elsif from < rb
    cmd << [from,la]
    cmd << [la,rb]
    cmd << [i,rb]
    pe[from] = pe[la]
    pe[la] = pe[rb]
    pe[rb] = pe[i]
    pos[pe[from]] = from
    pos[pe[la]] = la
    pos[pe[rb]] = rb
    num += 3
  else
    cmd << [i,rb]
    pe[rb] = pe[i]
    pos[pe[rb]] = rb
    num += 1
  end
  #p [i,from,num]
  #p pe
  #p pos
end
ra.upto(rb-1) do |i|
  from = pos[i]
  next if from==i
  if from > lb
    cmd << [from,la]
    cmd << [i,la]
    pe[from] = pe[la]
    pe[la] = pe[i]
    pos[pe[from]] = from
    pos[pe[la]] = la
    num += 2
  else
    cmd << [i,la]
    pe[la] = pe[i]
    pos[pe[la]] = la
    num += 1
  end
end
#p pe
if pe[1] != 1
  cmd << [1,n]
  num += 1
end
p num
cmd.each do |a,b|
  puts "#{a} #{b}"
end

def swap(pe,pos,cmd,a,b)
  tmp = pe[a]
  pe[a] = pe[b]
  pe[b] = tmp
  tmp = pos[pe[a]]
  pos[pe[a]] = pos[pe[b]]
  pos[pe[b]] = tmp
  cmd << [a,b]
end

n = gets.to_i
pe = [nil] + gets.split.map(&:to_i)
pos = []*(n+1)

n.times do |i|
  pos[pe[i+1]] = i+1
end

num = 0
cmd = []

la,lb,ra,rb = 1,n/2,n/2+1,n
2.upto(lb) do |i|
  from = pos[i]
  next if i==from
  if from < ra
    swap(pe,pos,cmd,from,rb)
    swap(pe,pos,cmd,i,rb)
    num += 2
  elsif from >= ra && from < rb
    swap(pe,pos,cmd,from,la)
    swap(pe,pos,cmd,la,rb)
    swap(pe,pos,cmd,i,rb)
    num += 3
  else
    swap(pe,pos,cmd,i,rb)
    num += 1
  end
  #p pe
  #p pos
  #puts
end

ra.upto(rb-1) do |i|
  from = pos[i]
  next if i==from
  if from > lb
    swap(pe,pos,cmd,from,la)
    swap(pe,pos,cmd,i,la)
    num += 2
  else
    swap(pe,pos,cmd,i,la)
    num += 1
  end
end

if pe[1] != 1
  swap(pe,pos,cmd,1,n)
  num += 1
end
p num
cmd.each do |a,b|
  puts "#{a} #{b}"
end

n = gets.to_i
pe = [nil] + gets.split.map(&:to_i)
pos = []*(n+1)
n.times do |i|
  pos[pe[i+1]] = i+1
end
#p pos

num = 0
cmd = []

la,lb,ra,rb = 1,n/2,n/2+1,n
2.upto(lb) do |i|
  from = pos[i]
  if from < ra
    cmd << [from,rb]
    cmd << [i,rb]
    pe[from] = pe[rb]
    pe[rb] = pe[i]
    pos[pe[from]] = from
    pos[pe[rb]] = rb
    num += 2
  elsif from < rb
    cmd << [from,la]
    cmd << [la,rb]
    cmd << [i,rb]
    pe[from] = pe[la]
    pe[la] = pe[rb]
    pe[rb] = pe[la]
    pos[pe[from]] = from
    pos[pe[la]] = la
    pos[pe[rb]] = rb
    num += 3
  else
    cmd << [i,rb]
    pe[rb] = pe[i]
    pos[pe[rb]] = rb
    num += 1
  end
  #p pe
  #p pos
end
ra.upto(rb-1) do |i|
  from = pos[i]
  if from > lb
    cmd << [from,la]
    cmd << [i,la]
    pe[from] = pe[la]
    pe[la] = pe[i]
    pos[pe[from]] = from
    pos[pe[la]] = la
    num += 2
  elsif from > la
    cmd <<[from,rb]
    cmd <<[rb,la]
    cmd <<[i,la]
    pe[from] = pe[rb]
    pe[rb] = pe[la]
    pe[la] = pe[rb]
    pos[pe[from]] = from
    pos[pe[rb]] = rb
    pos[pe[la]] = la
    num += 3
  else
    cmd << [i,la]
    pe[la] = pe[i]
    pos[pe[la]] = la
    num += 1
  end
end
#p pe
if pe[1] != 1
  cmd << [1,n]
  num += 1
end
p num
cmd.each do |a,b|
  puts "#{a} #{b}"
end

n = gets.to_i
pe = [nil] + gets.split.map(&:to_i)
pos = []*(n+1)
n.times do |i|
  pos[pe[i+1]] = i+1
end
#p pos

num = 0
cmd = []

la,lb,ra,rb = 1,n/2,n/2+1,n
2.upto(lb) do |i|
  from = pos[i]
  if from < ra
    cmd << [from,rb]
    cmd << [i,rb]
    pe[from] = pe[rb]
    pe[rb] = pe[i]
    pos[pe[from]] = from
    pos[pe[rb]] = rb
    num += 2
  else
    cmd << [from,la]
    cmd << [la,rb]
    cmd << [i,rb]
    pe[from] = pe[la]
    pe[la] = pe[rb]
    pe[rb] = pe[la]
    pos[pe[from]] = from
    pos[pe[la]] = la
    pos[pe[rb]] = rb
    num += 3
  end
  #p pe
  #p pos
end
ra.upto(rb-1) do |i|
  from = pos[i]
  if from > lb
    cmd << [from,la]
    cmd << [i,la]
    pe[from] = pe[la]
    pe[la] = pe[i]
    pos[pe[from]] = from
    pos[pe[la]] = la
    num += 2
  else
    cmd <<[from,rb]
    cmd <<[rb,la]
    cmd <<[i,la]
    pe[from] = pe[rb]
    pe[rb] = pe[la]
    pe[la] = pe[rb]
    pos[pe[from]] = from
    pos[pe[rb]] = rb
    pos[pe[la]] = la
    num += 3
  end
end
#p pe
if pe[1] != 1
  cmd << [1,n]
  num += 1
end
p num
cmd.each do |a,b|
  puts "#{a} #{b}"
end


Ashish has $$$n$$$ elements arranged in a line. These elements are represented by two integers $$$a_i$$$ — the value of the element and $$$b_i$$$ — the type of the element (there are only two possible types: $$$0$$$ and $$$1$$$). He wants to sort the elements in non-decreasing values of $$$a_i$$$.He can perform the following operation any number of times:  Select any two elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$ and swap them. That is, he can only swap two elements of different types in one move. Tell him if he can sort the elements in non-decreasing values of $$$a_i$$$ after performing any number of operations.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ $$$(1 \le n \le 500)$$$ — the size of the arrays. The second line contains $$$n$$$ integers $$$a_i$$$ $$$(1 \le a_i \le 10^5)$$$  — the value of the $$$i$$$-th element. The third line containts $$$n$$$ integers $$$b_i$$$ $$$(b_i \in \{0, 1\})$$$  — the type of the $$$i$$$-th element.

For each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value. You may print each letter in any case (upper or lower).

NoteFor the first case: The elements are already in sorted order.For the second case: Ashish may first swap elements at positions $$$1$$$ and $$$2$$$, then swap elements at positions $$$2$$$ and $$$3$$$.For the third case: The elements are already in sorted order.For the fourth case: No swap operations may be performed as there is no pair of elements $$$i$$$ and $$$j$$$ such that $$$b_i \ne b_j$$$. The elements cannot be sorted.For the fifth case: Ashish may swap elements at positions $$$3$$$ and $$$4$$$, then elements at positions $$$1$$$ and $$$2$$$.

def solve
  _ = gets
  a = gets.strip.split(' ').map(&:to_i)
  b = gets.strip.split(' ').map(&:to_i)
  x = 0
  y = 0
  b.each { |e|
    x += 1 if e.zero?
    y += 1 if !e.zero?
  }
  if !x.zero? && !y.zero? || a == a.sort
    puts "YES"
  else
    puts "NO"
  end
end

gets.strip.to_i.times { solve }

tasks_numbers = gets.chomp
answers = []
(1..tasks_numbers.to_i).each do
	numbers_qty = gets.chomp
	numbers = gets.chomp.split(" ")
	types = gets.chomp.split(" ")

	is_types_not_different = true
	index = 1
	prev_type = types.first
	while is_types_not_different && types.length > index do
		if prev_type != types[index]
			is_types_not_different = false
		end
		prev_type = types[index]
		index += 1
	end
	if is_types_not_different == false
		answers.push 'Yes'
		next
	end
	is_sort_asc = true
	index = 1
	prev_number = numbers.first.to_i
	while is_sort_asc && numbers.length > index do
		if prev_number > numbers[index].to_i
			is_sort_asc = false
		end
		prev_number = numbers[index].to_i
		index += 1
	end
	if is_sort_asc == true
		answers.push 'Yes'
	else
		answers.push 'No'
	end

end

answers.each do |answer|
	puts answer
end