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


For the given integer $$$n$$$ ($$$n > 2$$$) let's write down all the strings of length $$$n$$$ which contain $$$n-2$$$ letters 'a' and two letters 'b' in lexicographical (alphabetical) order.Recall that the string $$$s$$$ of length $$$n$$$ is lexicographically less than string $$$t$$$ of length $$$n$$$, if there exists such $$$i$$$ ($$$1 \le i \le n$$$), that $$$s_i < t_i$$$, and for any $$$j$$$ ($$$1 \le j < i$$$) $$$s_j = t_j$$$. The lexicographic comparison of strings is implemented by the operator < in modern programming languages.For example, if $$$n=5$$$ the strings are (the order does matter):  aaabb  aabab  aabba  abaab  ababa  abbaa  baaab  baaba  babaa  bbaaa It is easy to show that such a list of strings will contain exactly $$$\frac{n \cdot (n-1)}{2}$$$ strings.You are given $$$n$$$ ($$$n > 2$$$) and $$$k$$$ ($$$1 \le k \le \frac{n \cdot (n-1)}{2}$$$). Print the $$$k$$$-th string from the list.

The input contains one or more test cases. The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case is written on the the separate line containing two integers $$$n$$$ and $$$k$$$ ($$$3 \le n \le 10^5, 1 \le k \le \min(2\cdot10^9, \frac{n \cdot (n-1)}{2})$$$. The sum of values $$$n$$$ over all test cases in the test doesn't exceed $$$10^5$$$.

For each test case print the $$$k$$$-th string from the list of all described above strings of length $$$n$$$. Strings in the list are sorted lexicographically (alphabetically).

aaabb
aabab
baaba
bbaaa
abb
bab
aaaaabaaaaabaaaaaaaa

def tri(n)
	n * (n + 1) / 2
end

gets.to_i.times do
	n, k = gets.split.map &:to_i
	x = (1..10**9).bsearch{|i| tri(i) >= k}
	y = tri(x) - k
	ans = 'a' * n
	ans[n - x - 1] = 'b'
	ans[n - x + y] = 'b'
	puts ans
end

t = gets.to_i
t.times do
  n, k = gets.split.map(&:to_i)
  kk = 0
  for i in 1..(n-1) do
    if (kk + i) >= k
      j = k - kk - 1
      break
    end
    kk += i
  end
  s = "a" * n
  s[-1 - i] = "b"
  s[-1 - j] = "b"
  puts s
end

for run in 0...gets.to_i
	nums = gets.split(" ").map { |i| i.to_i }
	len = nums[0]
	loc = nums[1]
	t = 1
	i = 2
	until t >= loc
		t += i
		i += 1
	end
	rem = t - loc
	str = "a" * (len - i) + "b" + "a" * rem + "b" + "a" * (len - (len - i) - 1 - rem - 1)
	puts str
end

t = gets.to_i

1.upto(t) do
  n, k = gets.split(' ').map(&:to_i)

  sum = 0
  pos = 1
  i = 1
  while sum < k do
    sum += i
    pos += 1
    i   += 1
  end

  result = 'a'*n
  result[-pos] = 'b'
  result[-(k - sum + i - 1)] = 'b'

  puts result
end

# frozen_string_literal: true

def total(n, a)
  b = n - a
  tmp = (a + 1).upto(n).inject(:*) || 1
  2.upto(n - a) { |i| tmp /= i }
  tmp
end

test = gets.to_i
test.times do
  n, k = gets.chomp.split.map(&:to_i)
  a = n - 2
  n.downto(1) do |current|
    if current == 1
      if a > 0
        print 'a'
      else
        print 'b'
      end
    elsif a.zero?
      print 'b'
    elsif total(current - 1, a - 1) >= k
      print 'a'
      a -= 1
    else
      k -= total(current - 1, a - 1)
      print 'b'
    end
  end
  puts
end

t = gets.to_i
(1..t).each do
  arr = gets.split(' ')
  n = arr[0].to_i
  k = arr[1].to_i
  x = 1
  v = 0
  loop do
    if v+x < k
      v+=x
      x+=1
    else
      v+=x
      break
    end
  end
  ans = []
  (1..n-x-1).each do
    print "a"
  end
  rem = x-1
  print "b"
  (1..v-k).each do
    print "a"
    rem-=1
  end
  print "b"
  (1..rem).each do
    print "a"
  end
  puts("")

end


There are $$$n$$$ products in the shop. The price of the $$$i$$$-th product is $$$a_i$$$. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.In fact, the owner of the shop can change the price of some product $$$i$$$ in such a way that the difference between the old price of this product $$$a_i$$$ and the new price $$$b_i$$$ is at most $$$k$$$. In other words, the condition $$$|a_i - b_i| \le k$$$ should be satisfied ($$$|x|$$$ is the absolute value of $$$x$$$).He can change the price for each product not more than once. Note that he can leave the old prices for some products. The new price $$$b_i$$$ of each product $$$i$$$ should be positive (i.e. $$$b_i > 0$$$ should be satisfied for all $$$i$$$ from $$$1$$$ to $$$n$$$).Your task is to find out the maximum possible equal price $$$B$$$ of all productts with the restriction that for all products the condiion $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the same new price of all products) or report that it is impossible to find such price $$$B$$$.Note that the chosen price $$$B$$$ should be integer.You should answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) — the number of queries. Each query is presented by two lines. The first line of the query contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100, 1 \le k \le 10^8$$$) — the number of products and the value $$$k$$$. The second line of the query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the price of the $$$i$$$-th product.

Print $$$q$$$ integers, where the $$$i$$$-th integer is the answer $$$B$$$ on the $$$i$$$-th query. If it is impossible to equalize prices of all given products with restriction that for all products the condition $$$|a_i - B| \le k$$$ should be satisfied (where $$$a_i$$$ is the old price of the product and $$$B$$$ is the new equal price of all products), print -1. Otherwise print the maximum possible equal price of all products.

NoteIn the first example query you can choose the price $$$B=2$$$. It is easy to see that the difference between each old price and each new price $$$B=2$$$ is no more than $$$1$$$.In the second example query you can choose the price $$$B=6$$$ and then all the differences between old and new price $$$B=6$$$ will be no more than $$$2$$$.In the third example query you cannot choose any suitable price $$$B$$$. For any value $$$B$$$ at least one condition out of two will be violated: $$$|1-B| \le 2$$$, $$$|6-B| \le 2$$$.In the fourth example query all values $$$B$$$ between $$$1$$$ and $$$7$$$ are valid. But the maximum is $$$7$$$, so it's the answer.

q = gets.chomp.to_i

for ii in 1..q
  _min = 100000000
  _max = 0

  (n,k) = gets.chomp.split(" ")
  k = k.to_i
  gets.chomp.split(" ").each do |num|
    num = num.to_i
    _min = _min > num ? num : _min
    _max = _max > num ? _max : num
  end

  if _max - _min > k*2
    puts -1
  else
    puts _min + k
  end
end

t = gets.to_i
(1..t).each do
  res = 0
  read = gets.split(" ").map{|c| c.to_i}
  n = read[0]
  k = read[1]
  prices = gets.split(" ").map{|c| c.to_i}
  mini = 1000000000
  maxi = 0
  prices.each do |price|
    mini = price if price < mini
    maxi = price if price > maxi
  end
  if (mini-maxi).abs > k * 2
    res = -1
  else
    res = mini + k
  end
  puts res
end

q = gets.to_i
q.times do
  n,k = gets.split.map(&:to_i)
  a = gets.split.map(&:to_i)
  if a.min + k < a.max - k
    p -1
  else
    p a.min + k
  end
end

gets.to_i.times do
    n,k = gets.split.map(&:to_i)
    a = gets.split.map(&:to_i).sort
    if a[0]+k < a[-1]-k
        puts "-1"
    else
        puts a[0]+k
    end
end

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

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

def 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
########### ( ˘ω˘ )ｽﾔｧ… ###########
 q=gi
 q.times do
  n,k=gsmi
  a=gsmi.sort

  min=a[0]
  max=a[-1]

  if (max-min)>2*k
    puts -1
    next
  end

  puts min+k
 end

def test_cases(testCase)
    for interator in (0...testCase)
        (no_of_products, differ) = gets.chomp.split(' ').collect{|var| var.to_i}
        products = gets.chomp.split(' ').collect{|var| var.to_i}
        greatest_number = products.max
        smallest_number = products.min
        if(greatest_number - differ <= smallest_number + differ)
            puts smallest_number + differ
        else
            puts -1
        end
    end
end
testCase = gets.chomp.to_i
test_cases(testCase)


There are some ambiguities when one writes Berland names with the letters of the Latin alphabet.For example, the Berland sound u can be written in the Latin alphabet as "u", and can be written as "oo". For this reason, two words "ulyana" and "oolyana" denote the same name.The second ambiguity is about the Berland sound h: one can use both "h" and "kh" to write it. For example, the words "mihail" and "mikhail" denote the same name.There are n users registered on the Polycarp's website. Each of them indicated a name represented by the Latin letters. How many distinct names are there among them, if two ambiguities described above are taken into account?Formally, we assume that two words denote the same name, if using the replacements "u"  "oo" and "h"  "kh", you can make the words equal. One can make replacements in both directions, in any of the two words an arbitrary number of times. A letter that resulted from the previous replacement can participate in the next replacements.For example, the following pairs of words denote the same name:  "koouper" and "kuooper". Making the replacements described above, you can make both words to be equal: "koouper"  "kuuper" and "kuooper"  "kuuper".  "khun" and "kkkhoon". With the replacements described above you can make both words to be equal: "khun"  "khoon" and "kkkhoon"  "kkhoon"  "khoon". For a given list of words, find the minimal number of groups where the words in each group denote the same name.

The first line contains integer number n (2 ≤ n ≤ 400) — number of the words in the list. The following n lines contain words, one word per line. Each word consists of only lowercase Latin letters. The length of each word is between 1 and 20 letters inclusive.

Print the minimal number of groups where the words in each group denote the same name.

10
mihail
oolyana
kooooper
hoon
ulyana
koouper
mikhail
khun
kuooper
kkkhoon

9
hariton
hkariton
buoi
kkkhariton
boooi
bui
khariton
boui
boi

NoteThere are four groups of words in the first example. Words in each group denote same name:  "mihail", "mikhail"  "oolyana", "ulyana"  "kooooper", "koouper"  "hoon", "khun", "kkkhoon" There are five groups of words in the second example. Words in each group denote same name:  "hariton", "kkkhariton", "khariton"  "hkariton"  "buoi", "boooi", "boui"  "bui"  "boi" In the third example the words are equal, so they denote the same name.

def norm(s)
  s.gsub('u', 'oo').gsub('oo', 'u').gsub(/k+h/, 'h')
end

n = gets.to_i
ws = n.times.map{gets.strip}
puts ws.map{|w| norm(w)}.uniq.size

#! /usr/bin/env ruby

n = gets.to_i
a = (1..n).map { gets.gsub(/k+h/, 'h').gsub('u', 'oo') }.sort.uniq
puts a.size

number = ''
number = gets.chomp
n = number.to_i
res = {}
n.times do
   str = gets.chomp
   str.gsub!(/u/, 'oo')
   str.gsub!(/k+h/, 'h')
   res[str] = 1
end
puts res.size


A long time ago in some far country lived king Copa. After the recent king's reform, he got so large powers that started to keep the books by himself.The total income A of his kingdom during 0-th year is known, as well as the total income B during n-th year (these numbers can be negative — it means that there was a loss in the correspondent year). King wants to show financial stability. To do this, he needs to find common coefficient X — the coefficient of income growth during one year. This coefficient should satisfy the equation:A·Xn = B.Surely, the king is not going to do this job by himself, and demands you to find such number X.It is necessary to point out that the fractional numbers are not used in kingdom's economy. That's why all input numbers as well as coefficient X must be integers. The number X may be zero or negative.

The input contains three integers A, B, n (|A|, |B| ≤ 1000, 1 ≤ n ≤ 10).

Output the required integer coefficient X, or «No solution», if such a coefficient does not exist or it is fractional. If there are several possible solutions, output any of them.

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i
ret = "No solution"

for x in -1000..1000
	if A*(x**n) == B then
		ret = x
		break
	end
end
puts ret

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)+1e-9
if (r-r.to_i).abs>1e-8 then puts 'No solution';exit end
p r.to_i*sign

input=gets.split.map(&:to_i)
a=input[0]
b=input[1]
n=input[2]
-1000.upto(1000){|ans|
    if a*(ans**n)==b then
        puts ans
        exit
    end
}
puts "No solution"

a,b,n=gets.split.map &:to_i
-1000.upto(1000){|_|
	if a*_**n==b then
		p _
		exit
	end
}
print 'No solution'

#!/usr/bin/ruby

(a,b,n) =  gets.split(" ")
a = a.to_i()
b = b.to_i()
n = n.to_i()

for x in -1000..1000
  if a * (x**n) == b
    puts x
    exit()
  end
end

puts "No solution"
exit()

def pow(x,p)
  res = 1
  1.upto(p){
    res = res*x
  }
  return res
end

def bsearch(l, r, n, a, b)
  if (b%a != 0)
    return 0, true
  end

  c = b/a

  l.upto(r) { |i|
    return i, false if pow(i,n)==c
  }
  return 0, true
end

v = gets.split(' ')
A,B,n = v[0].to_i, v[1].to_i, v[2].to_i
no_solution = false
x=0
if n==0
    no_solution = true
  else
    x=0
  end if ((A==0) && (B==0))

no_solution = true if ((A==0) && (B!=0))

if n==0
    no_solution = true
  else
    x=0
  end if ((A>0) && (B==0))

if n.even?
    no_solution = true
  else
    x, no_solution = bsearch(-1001, 1001, n, A, B)
  end if ((A>0) && (B<0))

x, no_solution = bsearch(-1001, 1001, n, A, B) if ((A>0) && (B>0))

x, no_solution = bsearch(-1001, 1001, n, A, B) if ((A<0)&&(B<0))

if n==0
    no_solution = true
  else
    x=0
  end if ((A<0)&&(B==0))

if ((A<0)&&(B>0))
  if n.even?
    no_solution = true
  else
    x, no_solution = bsearch(-1001, 1001, n, A, B)
  end
end

if no_solution
  puts "No solution"
else
  puts x
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result - result.round).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.round.to_s.split(".")[0]
else
  puts "No solution"
end

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i

if(A==0)
	if(B==0)
		puts "1"
	else
		puts "No solution"
	end
else
	c = (Float(B)/A).abs**(1.0/n)
	 c = -c if (n%2>0  && (B/A)<0)
	wk = c.floor
	if (Float(wk) < c)
		puts "No solution"
	else
		puts wk
	end
end

s = gets
n1,n2,n3 = s.split(/ /)
A=n1.to_i
B=n2.to_i
n=n3.to_i

if(A==0)
	if(B==0)
		puts "5"
	else
		puts "No solution"
	end
else
	c = (Float(B)/A).abs**(1.0/n)
	 c = -c if (n%2>0  && (B/A)<0)
	wk = c.floor
	if (Float(wk) < c)
		puts "No solution"
	else
		puts wk
	end
end

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0 then p 1;exit end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)
if r!=r.to_i then puts 'No solution';exit end
p r.to_i*sign

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)
if r!=r.to_i then puts 'No solution';exit end
p r.to_i*sign

#!/usr/bin/ruby
a,b,n=gets.split.map(&:to_i)
if a==0
	puts b==0 ? 1 : 'No solution'
	exit
end
if a<0 then a=-a;b=-b end
sign=1
if b<0
	sign=-1 if n.odd?
	b=-b
end
r=(b.to_f/a)**(1.0/n)+1e-7
if (r-r.to_i).abs>1e-7 then puts 'No solution';exit end
p r.to_i*sign

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if result.to_s.split(".")[1].to_f == 0
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  puts "No solution"
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    puts result.to_s.split(".")[1].to_f
  end
  puts "No solution"

end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  puts "No solution"
end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result - result.round).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    result - result.round
  end
  puts "No solution"

end

mas = gets.split(" ")
a = mas[0].to_i
b = mas[1].to_i
n = mas[2].to_i

if (a == 0 && b == 0)
  puts 5
  exit
end

if ((a == 0) || (b % a != 0) || (b / a < 0 && n % 2 == 0))
  puts "No solution"
  exit
end

result = ((b/a).abs)**(1.0/n)

# /b/erd
if (result.to_s.split(".")[1].to_f).abs < 0.000000001
  if (b/a < 0)
    print "-"
  end
  print result.to_s.split(".")[0]
else
  if (a == 1 && b == 1000 && n == 3)
    result.to_s.split(".")[1].to_f
  end
  puts "No solution"

end


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. A permutation of length $$$n$$$ is a sequence such that each integer between $$$1$$$ and $$$n$$$ occurs exactly once in the sequence.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of the element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of the median of $$$p_l, p_{l+1}, \dots, p_r$$$ is exactly the given number $$$m$$$.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le m \le n$$$) — the length of the given sequence and the required value of the median. The second line contains a permutation $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). Each integer between $$$1$$$ and $$$n$$$ occurs in $$$p$$$ exactly once.

NoteIn the first example, the suitable pairs of indices are: $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(2, 3)$$$ and $$$(2, 4)$$$.

N, M = gets.split.map(&:to_i)
ps = gets.split.map(&:to_i)
index = ps.index(M)
lhash = Hash.new(0)
rhash = Hash.new(0)
lhash[0] = 1
rhash[0] = 1
sum = 0
(index-1).downto(0) do |i|
    sum += (ps[i] > M) ? 1 : -1
    lhash[sum] += 1
end
sum = 0
(index+1).upto(N-1) do |i|
    sum += (ps[i] > M) ? 1 : -1
    rhash[sum] += 1
end

ans = 0
lhash.keys.each do |i|
    ans += lhash[i] * (rhash[-i] + rhash[-i+1])
end
puts ans


Little X and Little Z are good friends. They always chat online. But both of them have schedules.Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the time when he gets up. If he gets up at time 0, he will be online at any moment of time between c1 and d1, between c2 and d2, ..., between cq and dq (all borders inclusive). But if he gets up at time t, these segments will be shifted by t. They become [ci + t, di + t] (for all i).If at a moment of time, both Little X and Little Z are online simultaneosly, they can chat online happily. You know that Little X can get up at an integer moment of time between l and r (both borders inclusive). Also you know that Little X wants to get up at the moment of time, that is suitable for chatting with Little Z (they must have at least one common moment of time in schedules). How many integer moments of time from the segment [l, r] suit for that?

The first line contains four space-separated integers p, q, l, r (1 ≤  p, q ≤ 50; 0 ≤ l ≤ r ≤ 1000). Each of the next p lines contains two space-separated integers ai, bi (0 ≤ ai < bi ≤ 1000). Each of the next q lines contains two space-separated integers cj, dj (0 ≤ cj < dj ≤ 1000). It's guaranteed that bi < ai + 1 and dj < cj + 1 for all valid i and j.

Output a single integer — the number of moments of time from the segment [l, r] which suit for online conversation.

p, q, l, r = STDIN.readline.split.map {|s| s.to_i }
x_pairs, z_pairs = [], []
p.times { x_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
x_bits = Array.new(1001, false)
x_pairs.each do |a, b|
	(a..b).each {|i| x_bits[i] = true }
end
q.times { z_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
count = 0
(l..r).each do |t|
	found = false
	z_pairs.each do |c, d|
		(c..d).each do |i|
			if x_bits[i+t]
				found = true
				break
			end
		end
		break if found
	end
	count += 1 if found
end
puts count

p, q, l, r = STDIN.readline.split.map {|s| s.to_i }
x_pairs, z_pairs = [], []
p.times { x_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
x = 0
x_pairs.each do |a, b|
	(a..b).each {|i| x |= (1 << i) }
end
q.times { z_pairs.push(STDIN.readline.split.map {|s| s.to_i }) }
z = 0
z_pairs.each do |c, d|
	(c..d).each {|i| z |= (1 << i) }
end
count = 0
(l..r).each {|t| count += 1 if (x & (z << t)) != 0 }
puts count

def check(ztime, xtime, t)
  ztime.each do |a, b|
    xtime.each do |c, d|
      break if c + t > b
      next if b < c + t
      return true if (c + t).between?(a, b) || (d + t).between?(a, b)
      return true if a.between?(c + t, d + t) || b.between?(c + t, d + t)
    end
  end

  false
end

p, q, l, r = gets.split.map(&:to_i)

ztime = []
p.times { ztime << gets.split.map(&:to_i) }

xtime = []
q.times { xtime << gets.split.map(&:to_i) }

puts l.upto(r).select { |t| check(ztime, xtime, t) }.size

p,q,l,r=gets.chomp.split.map(&:to_i)
a,b,c,ans=[],[],Array.new(1005,0),0
p.times do
	x,y=gets.chomp.split.map(&:to_i)
	a<<x;b<<y
end
q.times do
	x,y=gets.chomp.split.map(&:to_i)
	p.times do |i|
		j=a[i]-y
		while j<=b[i]-x
			if j>=l && j<=r && c[j]==0
				ans+=1
				c[j]=1
			end
			j+=1
		end
	end
end
puts ans

p, q, l, r = gets.chomp.split(' ').map(&:to_i)

x = []
p.times do
  a, b = gets.chomp.split(' ').map(&:to_i)
  #puts ">> #{a} #{b} #{a..b}"
  x.concat (a..b).to_a
end

y = []
q.times do
  c, d = gets.chomp.split(' ').map(&:to_i)
  y.concat (c..d).to_a
end
hy = {}
y.each { |e| hy[e] = true }

res = 0
(l..r).each do |i|
  found = false
  x.each do |xi|
    if hy[xi-i]
      found = true
      break
    end
  end

  res += 1 if found
end

puts res

p,q,l,r = gets.split(" ").map(&:to_i)
first = []
second = []
p.times do
	x,y = gets.split(" ").map(&:to_i)
	first << (x..y).to_a
end
first.flatten!

q.times do
	x,y = gets.split(" ").map(&:to_i)
	second << (x..y).to_a
end
second.flatten!
# puts "first #{first}"
# puts "sec #{second}"
count = 0
(l..r).each do |i|
	count += 1 unless (first & second.map{|a| a + i}).empty?
end
puts count

def read_next_line
  gets.chomp.split.map &:to_i
end

p, q, l, r = read_next_line
a = (p + q).times.map { read_next_line }
x, y = a[0...p], a[p..-1]
puts (l..r).to_a.select { |m|
  s = t = 0
  res = false
  while s < p
    t += 1 while t < q && x[s][0] > y[t][1] + m
    if t == q
      break
    elsif x[s][1] >= y[t][0] + m
      res = true
      break
    end
    s += 1
  end
  res
}.count

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
can = false
l.upto(r).each do |t|
  can = false
    ps.each do |pp|
  qs.each do |qq|
      next if pp[0] > qq[1] + t
      break if pp[1] < qq[0] + t
      if pp[0].between?((qq[0]+t), (qq[1]+t)) || pp[1].between?((qq[0]+t), (qq[1]+t)) || (qq[0]+t).between?(pp[0], pp[1]) || (qq[1]+t).between?(pp[0], pp[1])##(pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) || (pp[0] <= (qq[1]+t) && pp[1] >= (qq[1]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
  end
    break if can
    end
  count += 1 if can
end
# qs.each do |qq|
#   ps.each do |pp|
#     if pp[1] >= qq[0] && qq[0].between?(pp[0], pp[1])
#       count += 1
#     elsif pp[1] >= qq[0]
#       c = pp[0] - qq[1]
#       if c.between?(l, r)
#         count += 1
#       end
#     end
#   end
# end

puts count

p, q, l, r = gets.chomp.split(' ').map(&:to_i)

str1 = '0' * 1001
str2 = '0' * 1001

p.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str1[a..b]='1' * (b-a+1)
end

q.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str2[a..b]='1' * (b-a+1)
end

str2.prepend('0' * l)

ans = 0
(r-l+1).times do

	for i in 0..(-1+str1.length)
		if (str1[i]=='1' and str2[i]=='1')
			ans=ans+1
			break
		end
	end

	str2.prepend('0')

end
puts ans

#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2014 Szymon Sliwa <knight.erraunt@gmail.com>
#
# Distributed under terms of the MIT license.

p, q, l, r = gets.split.map(&:to_i)

tab_p, tab_q = [], []
p.times do
    tab_p << gets.split.map(&:to_i)
end
q.times do
    tab_q << gets.split.map(&:to_i)
end

p_present = {}
tab_p.each do |x|
    (x[0]..x[1]).each do |y|
        p_present[y] = true
    end
end

possible_diffs = {}
tab_q.each do |x|
    (x[0]..x[1]).each do |y|
        p_present.to_a.map do |a|
            possible_diffs[a[0]-y] = true
        end
    end
end

puts possible_diffs.to_a.select{|a| a[0] >= l && a[0] <= r}.size

def check(xtime, ztime, getup)
  xtime.each do |a, b|
    ztime.each do |c, d|
      return true if (c + getup).between?(a, b) || (d + getup).between?(a, b)
    end
  end

  false
end

p, q, l, r = gets.split.map(&:to_i)

xtime = []
p.times { xtime << gets.split.map(&:to_i) }

ztime = []
q.times { ztime << gets.split.map(&:to_i) }

puts l.upto(r).select { |getup| check(xtime, ztime, getup) }.size

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
(l..r).each do |t|
  can= false
  qs.each do |qq|
    ps.each do |pp|
      if (pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
    end
    break if can
  end
  count += 1 if can
end

puts count

p, q, l, r = gets.split.map(&:to_i)
ps, qs = [], []
p.times {ps << gets.split.map(&:to_i)}
q.times {qs << gets.split.map(&:to_i)}
count = 0
(l..r).each do |t|
  can= false
  qs.each do |qq|
    ps.each do |pp|
      if (pp[0] <= (qq[0]+t) && pp[1] >= (qq[0]+t)) || (pp[0] <= (qq[1]+t) && pp[1] >= (qq[1]+t)) #((pp[0]..pp[1]).to_a & ((qq[0]+t)..(qq[1]+t)).to_a).any?
        can = true
        break
      end
    end
    break if can
  end
  count += 1 if can
end

puts count

p, q, l, r = gets.chomp.split(' ').map(&:to_i)

str1 = '0' * 40
str2 = '0' * 40

p.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str1[(a-1)..(b-1)]='1' * (b-a+1)
end

q.times do
	a, b = gets.chomp.split(' ').map(&:to_i)
	str2[(a-1)..(b-1)]='1' * (b-a+1)
end

str2.prepend('0' * l)

ans = 0
(r-l+1).times do

	for i in 0..(-1+str1.length)
		if (str1[i]=='1' and str2[i]=='1')
			ans=ans+1
			break
		end
	end

	str2.prepend('0')

end
puts ans


Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.There are $$$n$$$ banknote denominations on Mars: the value of $$$i$$$-th banknote is $$$a_i$$$. Natasha has an infinite number of banknotes of each denomination.Martians have $$$k$$$ fingers on their hands, so they use a number system with base $$$k$$$. In addition, the Martians consider the digit $$$d$$$ (in the number system with base $$$k$$$) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base $$$k$$$ is $$$d$$$, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.Determine for which values $$$d$$$ Natasha can make the Martians happy.Natasha can use only her banknotes. Martians don't give her change.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100\,000$$$, $$$2 \le k \le 100\,000$$$) — the number of denominations of banknotes and the base of the number system on Mars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — denominations of banknotes on Mars. All numbers are given in decimal notation.

On the first line output the number of values $$$d$$$ for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation.

NoteConsider the first test case. It uses the octal number system.If you take one banknote with the value of $$$12$$$, you will get $$$14_8$$$ in octal system. The last digit is $$$4_8$$$.If you take one banknote with the value of $$$12$$$ and one banknote with the value of $$$20$$$, the total value will be $$$32$$$. In the octal system, it is $$$40_8$$$. The last digit is $$$0_8$$$.If you take two banknotes with the value of $$$20$$$, the total value will be $$$40$$$, this is $$$50_8$$$ in the octal system. The last digit is $$$0_8$$$.No other digits other than $$$0_8$$$ and $$$4_8$$$ can be obtained. Digits $$$0_8$$$ and $$$4_8$$$ could also be obtained in other ways.The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.

N, K = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)
num = K
as.each do |a|
    num = num.gcd(a)
end
puts K/num
puts (0...(K/num)).map{|i| i*num}.join(' ')