fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  pos = 0
  while i = str.index(w, pos)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
    pos += 1
  end
end
puts ret

#sharyo
def isupper(c)
    if (/[[:upper:]]/.match(c))
	return true
	end
 return false
end
n=gets.to_i
m=Hash.new
v=Array.new
for i in 0..n-1
   x=gets.chop
   y=""
  x.split('').each{|j|
   	y+=j.downcase
   }
   m[y]=true
end
a=gets.chop.split('')
b=a.join
n=b.length

b=b.split('')

for i in 0..n-1
a[i]=a[i].downcase
end
c=Array.new(n,false)

for i in 0..n-1
	x=""
	for j in i..n-1
		x+=a[j]
		if m[x]
			v.push([i,j])
		end
	end
end
v.each do |(x,y)|
	for j in x..y
		c[j]=true
	end
end
z=gets.chop
for i in 0..n-1
	next unless c[i]
	if z.downcase!=b[i].downcase
		if 	isupper(b[i])
			b[i]=z.upcase
		else
            b[i]=z
		end

	elsif b[i].downcase=='a'
        if isupper(b[i])
			b[i]='B'
		else
            b[i]='b'
		end

	else
		if 	isupper(b[i])
			b[i]='A'
		else
            b[i]='a'
		end
	end

end

print b.join

n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i].downcase == c.downcase
      if t[i].downcase == t[i]
        t[i] = c == ?a || c == ?A ? ?b : ?a
      else
        t[i] = c == ?a || c == ?A ? ?B : ?A
      end
    else
      if t[i].downcase == t[i]
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t

n = gets.chomp.to_i
ss = Array.new(n)
for i in 1..n
  ss[i-1] = gets.chomp.upcase
end
s0 = gets.chomp
c = gets.chomp
s = s0.upcase
ii = Array.new(s.length).map!{|x| false}
for i in 1..n
  previdx = 0
  while true
    wkidx = s.index(ss[i-1], previdx)
    if wkidx != nil then
      for j in 0..ss[i-1].length-1
        ii[wkidx+j] = true
      end
    else
      break
    end
    previdx = wkidx+1
  end
end

c2 = c.upcase
for i in 0..s0.length-1
  next if ii[i] == false
  wkup = false
  wkup = true if s0[i] == s[i]
  wk = c
  if s[i] == c2 then
    if c == "a" then
      wk = "b"
    else
      wk = "a"
    end
  end
  wk = wk.upcase if wkup
  s0[i] = wk
end
puts s0

def optimal_letter(ch,l)
	return(ch<?a ? l.upcase : l) if ch.downcase!=l
	case ch
		when ?a then ?b
		when ?A then ?B
		when ?b..?z then ?a
		else ?A
	end
end

s=1.upto(gets.to_i).map{gets.upcase.chomp}
w,l=gets.chomp,gets.chomp
up_w=w.upcase
replace_flag=[false]*w.size
s.uniq.each{|str|
	size=str.size
	0.upto(w.size-size).map{|idx|up_w.index(str,idx)}.uniq.compact.each{|idx|
		replace_flag[idx...idx+size]=[true]*size
	}
}
w.size.times{|i|print replace_flag[i] ? optimal_letter(w[i],l) : w[i]}

#sharyo
def isupper(c)
    if (/[[:upper:]]/.match(c))
	return true
	end
 return false
end
n=gets.to_i
m=Hash.new
v=Array.new
for i in 0..n-1
   x=gets.chop
   y=""
  x.split('').each{|j|
   	y+=j.downcase
   }
   m[y]=true
end
a=gets.chop.split('')
b=a.join
n=b.length

b=b.split('')

for i in 0..n-1
a[i]=a[i].downcase
end
c=Array.new(n,false)

for i in 0..n-1
	x=""
	for j in i..n-1
		x+=a[j]
		if m[x]
			v.push([i,j])
		end
	end
end
v.each do |(x,y)|
	for j in x..y
		c[j]=true
	end
end
z=gets.chop
for i in 0..n-1
	next unless c[i]
	if z.downcase!=b[i]
		if 	isupper(b[i])
			b[i]=z.upcase
		else
            b[i]=z
		end

	elsif b[i].downcase=='a'
        if isupper(b[i])
			b[i]='B'
		else
            b[i]='b'
		end

	else
		if 	isupper(b[i])
			b[i]='A'
		else
            b[i]='a'
		end
	end

end

print b.join

begin
n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if /[a-z]/.match?(t[i])
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t
rescue => e
  puts e
end

begin
n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if t[i].match?(/[a-z]/)
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t
end
rescue => e
  puts e
end

n = gets.to_i
ps = (1..n).map { |s| gets.strip }
t = gets.strip
c = gets.strip
x = [0] * t.size
(0...t.size).each do |i|
  ps.each do |s|
    x[i, s.size] = [1] * s.size if t[i, s.size].downcase == s.downcase
  end
end
x.size.times do |i|
  if x[i] == 1
    if t[i] == c
      t[i] = c == ?a ? ?b : ?a
    else
      if t[i].downcase == t[i]
        t[i] = c
      else
        t[i] = c.upcase
      end
    end
  end
end
puts t

def optimal_letter(ch,l)
	return(ch<?a ? l.upcase : l) if ch.downcase!=l
	case ch
		when ?a then ?b
		when ?A then ?B
		when ?b..?z then ?a
		else ?A
	end
end
AST=?*.ord
gets
forbidden_substrings=gets(nil).split
letter,w=2.times.map{forbidden_substrings.pop}
replace_flag=forbidden_substrings.map{|str|w.gsub(/#{str}/i,?**str.size).bytes.to_a}.transpose.map{|bytes|bytes.any?{|b|b==AST}}
w.size.times{|i|print replace_flag[i] ? optimal_letter(w[i],letter) : w[i]}

fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  if i = str.index(w)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
  end
end
puts ret

fw = []
gets.to_i.times do
  fw << gets.strip.downcase
end
ret = gets.strip
str = ret.downcase
letter = gets.strip
fw.each do |w|
  pos = 0
  while i = str.index(w, pos)
    (i...(i + w.size)).each do |n|
      if str[n] == letter
        if str[n] == 'a'
          c = 'b'
        else
          c = 'a'
        end
      else
        c = letter
      end
      ret[n] = ret[n] == ret[n].upcase ? c.upcase : c
    end
    pos += w.size
  end
end
puts ret


gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }
  visited = [false] * c.size
  result = 1
  c.each_index do |i|
    result = (result * 2) % 1000000007 unless visited[i]
    j = i
    while !visited[j]
      visited[j] = true
      j = c[j][1]
    end
  end
  puts result
end

gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }
  visited = [false] * c.size
  result = 0
  c.each_index do |i|
    result += 1 unless visited[i]
    j = i
    while !visited[j]
      visited[j] = true
      j = c[j][1]
    end
  end
  puts 2.pow(result, 1000000007)
end

gets.to_s.to_i.times do
  n = gets.to_s.to_i
  a = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  b = gets.to_s.strip.split.map {|x| x.to_i - 1 }
  c = a.zip(b).sort {|x, y| x[0] <=> y[0] }.map {|x| x[1] }
  result = 1
  c.each_with_index do |ci, i|
    next if ci < 0
    result = (result * 2) % 1000000007
    j = i
    c[j], j = -1, c[j] until j < 0
  end
  puts result
end


a = $<.read.split.map(&:to_i)
p (1.upto(a[0]).map do |i|
  c = 1
  c += 1 while (i = a[i]) != -1
  c
end.max)

a=gets.chomp.to_i
ar=[]
a.times do
ar << gets.chomp.to_i
end
max=0
0.upto(a-1) do |i|
temp=1
k=ar[i]
loop do
break if k==-1
k=ar[k-1]
temp+=1
end
if temp >max
max=temp
end
end
puts "#{max}"

n = gets.to_i
mg = n.times.map{gets.to_i}
mx = 0
n.times do |i|
  m = i
  cnt = 1
  n.times do
    if mg[m] == -1
      mx = [cnt, mx].max
      break
    end
    m = mg[m] - 1
    cnt += 1
  end
end
puts mx

n = gets.to_i
mg = [nil] + n.times.map{gets.to_i}
$e = Array.new(n + 1){Array.new}
1.upto(n){|i| $e[[0, mg[i]].max] << i}
$cnt = []

def dfs(u, lv)
  $cnt[u] = lv
  $e[u].each do |v|
    dfs(v, lv + 1)
  end
end

dfs(0, 0)
puts $cnt.max

def dep(v)
  result = 1
  pos = v
  while pos > 0
    result += 1
    pos = $a[pos]
  end

  result
end

n = gets.to_i

$a = (1..n).map { gets.to_i }
$a.unshift 0
puts $a.map { |x| dep(x) }.max

n=gets.to_i
a=(0..n).map{[]}
b=[]

n.times{|i|
	e=i+1
	e2=gets.to_i
	a[e2]<<e if e2!=-1
	b<<e if e2==-1
}
ans=1
while true
	b2=[]
	while !b.empty?
		no=b.shift
		a[no].each{|no2|
			b2<<no2
		}
	end
	break if b2.empty?
	b2.each{|e|
		b<<e
	}
	ans=ans+1
end
puts ans

# 115A

a = (0...gets.to_i).map { gets.to_i - 1 }
max = 1
a.each { |x|
  len = 1
  while x != -2
    x = a[x]
    len += 1
  end
  max = len if len > max
}
puts max

# The following O(n) solution works on my machine but fails on codeforces with RUNTIME_ERROR
=begin
class Node
  attr_accessor :parent
  attr_reader :children

  def initialize()
    @children = []
  end

  def len
    @children.size > 0 ? @children.map(&:len).max + 1 : 1
  end
end

n = gets.to_i
nodes = Array.new(n)
n.times { |i|
  p = gets.to_i - 1
  node = nodes[i] || Node.new
  if p >= 0
    parent = nodes[p] || Node.new
    node.parent = parent
    parent.children << node
    nodes[p] = parent
  end
  nodes[i] = node
}

puts nodes.select { |node| node.parent.nil? }.map(&:len).max
=end

n=gets.to_i
g=Array.new(n+1)
(1).upto(n) {|i| g[i]=[]}
q=Queue.new
(1).upto(n) do |i|
  p=gets.to_i
  g[p].push(i) if(p!=-1)
  q.push([i,1]) if(p==-1)
end
mx=0
while !(q.empty?) do
  cur = q.pop
  mx=cur[1]
  g[cur[0]].each do |node|
    q.push([node,mx+1])
  end
end
puts mx

n = gets.to_i
e = Array.new(n) { [] }
roots = []
n.times {|i|
  j = gets.to_i
  if j == -1
    roots << i
  else
    e[j-1] << i
  end
}

def depth(i, e)
  return 1 if e[i].empty?
  e[i].map{|c| depth(c, e)}.max + 1
end

puts roots.map{|r| depth(r, e)}.max

n = gets.chomp.to_i
maxlevel = 0
a = Array.new(n)
for i in 0..n-1
  a[i] = gets.chomp.to_i
end
for i in 0..n-1
  lvl = 1
  j = i
  while a[j] != -1
    j = a[j]-1
    lvl += 1
  end
  maxlevel = lvl if maxlevel < lvl
end
puts maxlevel

n = gets.strip.to_i

pairs = []
rank = Array.new(n,0)
n.times do |i|
	man = gets.strip.to_i
	if man ==-1
		rank[i] = 1
	else
		pairs << [man, i+1]
	end
end

while rank.include? 0
	pairs.each do |v|
		u,l = v
		next if rank[l-1]!=0

		surank = rank[u-1]
		if surank!=0
			rank[l-1] = surank+1
		end
	end
end

puts rank.max

num = 0
answer = 0
employees = []

while line = STDIN.gets
  count = 0
  num += 1
  if (/exit/ =~ line)
    break;
  elsif (num == 1)
    line = line.chomp.to_i
    employee_count = line
  else
    employees.push([nil, line = line.chomp.to_i])
  end
end

employees.each do |employee|
  count = 0
  employee_tmp = employee
  while true
    count += 1
    if employee_tmp[1] == -1
      break
    else
      employee_tmp = employees[employee_tmp[1]-1]
    end
  end
  if count > answer
    answer = count
  end
end
STDOUT.puts answer

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
visited = Hash.new
-1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 0
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				if !h[x].nil?
					q.push(x)
				end
			end
		end
	end
end

# print visited
print visited.values.max

def solve(x)
        if $p[x]<0 then
                return 0
        end
        if $dp[x]>=0 then
                return $dp[x]
        end
        return $dp[x]=solve($p[x])+1
end
n=gets.to_i
$p=[]
n.times{|i|
        $p.push(gets.to_i-1)
}
$dp=Array.new(n,-1)
ans=0
n.times{|i|
        ans=[ans,solve(i)].max
}
p ans+1

class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(index1, index2)
    if vertices[index1].nil? then
      vertices[index1] = List.new(index2, nil)
    else
      vert = List.new(index2, vertices[index1])
      vertices[index1] = List.new(index2, vertices[index1])
    end
  end

  def print_edges
    vertices.each_with_index do |vertex, index|
      while !vertex.nil? do
        # puts "edge #{index} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end
end

def depth(graph, index)
  return 1 if graph.vertices[index].nil?
  max_depth = depth(graph, graph.vertices[index].element)
  next_vertex = graph.vertices[index].next_elem
  while !next_vertex.nil? do
    current_max_depth = depth(graph, next_vertex.element)
    max_depth = [max_depth, current_max_depth].max
    next_vertex = next_vertex.next_elem
  end
  return max_depth + 1
end

employees = Graph.new([])
root_managers = []
n = gets.strip.to_i
n.times do |i|
  manager = gets.strip.to_i
  if manager == -1 then
    root_managers.push(i)
  else
    employees.add_edge(manager - 1, i)
  end
end
employees.print_edges
# puts "root managerts: #{root_managers.join(" ")}"
max_depth = 1
root_managers.each do |i|
  if !employees.vertices[i].nil?
    max_depth = [depth(employees, i), max_depth].max
  end
end
puts max_depth

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

# 이거 LCA (Lowest Common Ancestor) 문제로 접근하면 간단하고,
# 그림을 적어도 한번은 그려보길 권함
# depth마다 수평하게 잘라내면 어떤 상사도 겹치지 않는다.
# 즉, 최고 depth의 수는 만들 수 있는 적절한 그룹의 수가 된다.

n = gets.to_i
ee = []
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
map = {}
groups_max = 0
for i in 0...n
    map[i] = []
    j = i
    loop do
        sup = ee[j]
        if sup < 0
            break
        else
            map[i] << sup
            j = sup
        end
    end

    if map[i].length > groups_max
        groups_max = map[i].length
    end
end

puts groups_max + 1 # value excludes itself

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

n = gets.to_i
ee = []
LOCATED = 2001
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
groups = 0
i = 0
# p ee
while ee.count(LOCATED) < n
    forming = []
    forming << i

    loop do
        i += 1
        break if i >= n

        if ee[i] == LOCATED
            next
        else
            sup_resides_in_forming = false
            j = i
            while j < ee.length
                if ee[j] == LOCATED || ee[j] < 0
                    # safely append it
                    break
                elsif forming.include?(ee[j])
                    sup_resides_in_forming = true
                    break
                else
                    j = ee[j]
                end
            end

            unless sup_resides_in_forming
                forming << i
            end
        end
    end

    # p forming
    unless forming.empty?
        # if reaches end, group them and clear
        forming.each { |idx|
            ee[idx] = LOCATED
        }
        groups += 1
        forming.clear
    end

    # p ee
    ni = ee.index { |x| x != LOCATED }
    if ni == nil
        # p "--- #{ni}"
        break
    else
        i = ni
    end
end

puts groups

# coding: utf-8

# if __FILE__ == $0
# end

n = gets.to_i
ee = []
n.times {
    ee << gets.to_i
}

ee.sort!
prev = nil
bcounter = 0
ee.each { |i|
    if prev != i
        bcounter += 1
        prev = i
    end
}

puts bcounter

# coding: utf-8

# if __FILE__ == $0
# end

# 5
# -1 : 1번 사원의 상사는 없음
# 1  : 2번 사원의 상사는 1번임
# 2  : 3번 사원의 상사는 2번임
# 1  : 4번 사원의 상사는 1번임
# -1 : 5번 사원의 상사는 없음
# transitive를 허용하지 않음(2의 상사는 3인데, 3의 상사는 1이면 2-1은 같이 있을 수 없다)

n = gets.to_i
ee = []
LOCATED = 2001
n.times {
    ee << gets.to_i - 1 # -1 -> -2
}
groups = 0
i = 0
# p ee
while ee.count(LOCATED) < n
    forming = []
    forming << i

    loop do
        i += 1
        break if i >= n

        if ee[i] == LOCATED
            next
        else
            sup_resides_in_forming = false
            j = i
            while j < ee.length && !sup_resides_in_forming
                if ee[j] == LOCATED
                    # safely append it
                    break
                elsif ee[j] < 0
                    # check him/herself is a superior from someone
                    for idx in forming
                        sup = ee[idx]
                        if sup == j
                            sup_resides_in_forming = true
                            break
                        end
                    end

                    break
                elsif forming.include?(ee[j])
                    sup_resides_in_forming = true
                    break
                else
                    j = ee[j]
                end
            end

            unless sup_resides_in_forming
                forming << i
            end
        end
    end

    # p forming
    unless forming.empty?
        # if reaches end, group them and clear
        forming.each { |idx|
            ee[idx] = LOCATED
        }
        groups += 1
        forming.clear
    end

    # p ee
    ni = ee.index { |x| x != LOCATED }
    if ni == nil
        # p "--- #{ni}"
        break
    else
        i = ni
    end
end

puts groups

n = gets.to_i
h = Hash.new(0)
n.times do
  i = gets.to_i
  h[i] += 1 if i != -1
end
p h.values.max + 1

n = gets.to_i

puts 1 + (1..n).count { gets.to_i == -1 }

# 115A

class Node
  attr_accessor :parent
  attr_reader :children

  def initialize()
    @children = []
  end

  def len
    @children.size > 0 ? @children.map(&:len).max + 1 : 1
  end
end

n = gets.to_i
nodes = Array.new(n)
n.times { |i|
  p = gets.to_i - 1
  node = nodes[i] || Node.new
  if p >= 0
    parent = nodes[p] || Node.new
    node.parent = parent
    parent.children << node
    nodes[p] = parent
  end
  nodes[i] = node
  if i >= 90
    puts p
  end
}

puts nodes.select { |node| node.parent.nil? }.map(&:len).max

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
visited = Hash.new
if !h[-1].nil?
	visited[-1] = 1
end

1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 1
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				if !h[x].nil?
					q.push(x)
				end
			end
		end
	end
end

print visited.values.max

n = gets.chomp.to_i
h = Hash.new

1.upto(n).each do |i|
	v = gets.chomp.to_i
	h[v] ||= []
	h[v] << i
end

# p h
ac = 0
if !h[-1].nil?
	ac += 1
end

visited = Hash.new

1.upto(n) do |i|
	next if h[i].nil? || !visited[i].nil?
	visited[i] = 1
	q = Queue.new
	q.push(i)
	while(!q.empty?)
		f = q.pop
		next if h[f].nil?

		h[f].each do |x|
			if visited[x].nil?
				visited[x] = visited[f] + 1
				ac = [ac, visited[x]].max
				q.push(x)
			end
		end
	end
end

print ac

class List
  attr_accessor :element, :next_elem

  def initialize(element, next_elem)
    @element = element
    @next_elem = next_elem
  end
end

class Graph
  attr_accessor :vertices

  def initialize(vertices)
    @vertices = vertices
  end

  def add_edge(index1, index2)
    if vertices[index1].nil? then
      vertices[index1] = List.new(index2, nil)
    else
      vert = List.new(index2, vertices[index1])
      vertices[index1] = List.new(index2, vertices[index1])
    end
  end

  def print_edges
    vertices.each_with_index do |vertex, index|
      while !vertex.nil? do
        # puts "edge #{index} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end
end

def depth(graph, index)
  return 1 if graph.vertices[index].nil?
  max_depth = depth(graph, graph.vertices[index].element)
  next_vertex = graph.vertices[index].next_elem
  while !next_vertex.nil? do
    current_max_depth = depth(graph, next_vertex.element)
    max_depth = [max_depth, current_max_depth].max
    next_vertex = next_vertex.next_elem
  end
  return max_depth + 1
end

employees = Graph.new([])
root_managers = []
n = gets.strip.to_i
n.times do |i|
  manager = gets.strip.to_i
  if manager == -1 then
    root_managers.push(i)
  else
    employees.add_edge(manager - 1, i)
  end
end
employees.print_edges
# puts "root managerts: #{root_managers.join(" ")}"
max_depth = 0
root_managers.each do |i|
  current_depth = 0
  if !employees.vertices[i].nil?
    max_depth = [depth(employees, i), max_depth].max
  end
end
puts max_depth


t = gets.to_i
(1..t).each do
  n = gets.to_i
  s = 0
  p = 1
  i = 2
  while n > 0
    d = i / p.gcd(i)
    s += i * (n - n / d)
    n /= d
    p *= d
    i += 1
  end
  puts s % (10 ** 9 + 7)
end


#!/usr/bin/ruby

n, k = STDIN.readline.split.map {|s| s.to_i }
arr = STDIN.readline.split.map {|s| s.to_i }.sort
sums = [0]
sum = 0
arr.each {|x| sums.push(sum += x) }
best_count, best_value = -1, -1
n.times do |i|
	low, high = 0, i
	while low != high
		pos = (low+high)/2
		width = i-pos+1
		need = width*arr[i] - sums[i+1] + sums[pos]
		if need > k
			low = pos+1
		else
			high = pos
		end
	end
	count = i-low+1
	if count > best_count
		best_count = count
		best_value = arr[i]
	end
end
puts '%d %d' % [best_count, best_value]

#!/usr/bin/ruby

n, k = STDIN.readline.split.map {|s| s.to_i }
arr = STDIN.readline.split.map {|s| s.to_i }.sort
sums = [0]
sum = 0
arr.each {|x| sums.push(sum += x) }
best_count, best_value = 1, arr[0]
pos = 0
(1..n-1).each do |i|
	while true
		count = i-pos+1
		need = count*arr[i] - sums[i+1] + sums[pos]
		if need <= k
			if count > best_count
				best_count = count
				best_value = arr[i]
			end
			break
		end
		pos += 1
	end
end
puts '%d %d' % [best_count, best_value]


def gs() = gets.chomp
def gi() = gets.to_i
def gli() = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

T = gi
T.times do
  s = gs.split("").map(&:to_i)
  if s.count { |x| x.even? }.zero?
    puts '-1'
  else
    if s[-1].even?
      puts 0
    elsif s[0].even?
      puts 1
    else
      puts 2
    end
  end
end

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

inputs.each do |inp|
    if inp.to_i % 2 == 0
        puts "0"
        next
    end
    if !inp.chars.any?{|c| c.to_i % 2 == 0}
        puts "-1"
        next
    end
    if inp[0].to_i % 2 == 0
        puts "1"
        next
    end

    puts "2"
end

t = gets.to_i
ans = []
t.times do |i|
  n = gets.chomp.split("").map(&:to_i)
  if n[-1] % 2 == 0
    ans << 0
  elsif n[0] % 2 == 0
    ans << 1
  elsif n.any?{|v| v%2==0}
    ans << 2
  else
    ans << -1
  end
end
puts ans

def solve
  n = gets.strip.split('').map(&:to_i)
  if n.last.even?
    puts 0
  elsif n.first.even?
    puts 1
  elsif n.any?(&:even?)
    puts 2
  else
    puts '-1'
  end
end

gets.strip.to_i.times { solve }

t = gets.to_i
t.times do
  s = gets.chomp.chars.map(&:to_i)
  if s.all?(&:odd?)
    puts -1
  elsif s[-1].even?
    puts 0
  elsif s[0].even?
    puts 1
  else
    puts 2
  end
end

t = gets.split
t = t[0].to_i

for i in 0..t-1 do
  b = gets.split
  a = b[0].split("")
  if b[0].to_i % 2 == 0
    puts 0
  elsif a[0].to_i % 2 == 0
    puts 1
  else
    n = a.length
    s = 0
    for j in 1..n-1 do
      if a[j].to_i % 2 == 0
        puts 2
        s = 1
        break
      end
    end
    if s==0
      puts -1
    end
  end
end

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

inputs.each do |inp|
    if inp.to_i % 2 == 0
        puts "0"
        next
    end
    if inp.length == 1
        puts "-1"
        next
    end
    if inp[0].to_i % 2 == 0
        puts "1"
        next
    end

    puts "2"
end


_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.max

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  if p_odds.length % 2 == 0
    if !m_odd.nil? && m_odd + p_odds.first > 0
      answer += m_odd
    else
      p_odds.shift
    end
  end
  # p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

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

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    odd_neg.push(-odd_pos.min)
    exchange = (odd_pos.length % 2 == 0 ? [-odd_pos.min, odd_neg.max].max : 0)
    puts (even.reduce(0, :+) + odd_pos.reduce(:+) + exchange)
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

gets
res, aa = 0, []
gets.split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? do
  a = aa.pop + aa.pop
  break if a <= 0
  res += a
end
p res

def ascan; gets.split.map(&:to_i); end
def scan; gets.to_i; end

gets
aa = ascan.sort!

ao = []
ae = []
aa.each{|e| if e.odd? ; ao << e ; else ; ae << e ; end }

best = ae.inject(0){|s,e| 0 < e ? s+e : s}

best += ao.pop

while 2<=ao.size
    x,y = ao.pop(2)
    break if x+y <= 0
    best += x+y
end

p best

gets
res, aa = 0, []
gets.split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? || (a = aa.pop + aa.pop) <= 0
  res += a
end
p res

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.first

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

def sum(arr)
  arr.inject(0) { |sum, x| sum + x }
end

p_even_sum = xs.select { |x| x > 0 && x % 2 == 0 }.inject(0) { |sum, x| sum + x }
p_odds = xs.select { |x| x > 0 && x % 2 == 1 }.sort
m_odd = xs.select { |x| x < 0 && x % 2 == 1 }.max

answer = p_even_sum

if p_odds.length == 0
  answer += m_odd
else
  p_odds.shift if p_odds.length % 2 == 0
  answer += sum(p_odds)
end

puts answer

# -6004 4882 9052 413 6056 4306 9946 -4616 -6135 906 -1718 5252 -2866 9061 4046

_n = STDIN.gets.chomp.to_i
xs = STDIN.gets.chomp.split.map { |x| x.to_i }

max_odd = nil
max_even = 0

xs.each do |x|
  if x % 2 == 1
    if max_odd.nil?
      max_odd = x
    else
      max_odd = [ max_odd, max_even + x ].max
      max_even = [ max_even, max_odd + x ].max
    end
  else
    max_even = [ max_even, max_even + x ].max
  end
end

puts max_odd

def ascan; gets.split.map(&:to_i); end
def scan; gets.to_i; end

gets
aa = ascan.sort!

ao = []
ae = []
aa.each{|e| if e.odd? ; ao << e ; else ; ae << e ; end }

best = ae.inject(0){|s,e| 0 < e ? e : 0}

best += ao.pop

while 2<=ao.size
    x,y = ao.pop(2)
    break if x+y <= 0
    best += x+y
end

p best

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

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    puts (even.reduce(0, :+) + odd_pos.reduce(:+) - (odd_pos.length % 2 == 0 ? odd_pos.min : 0))
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

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

even = data.select { |x| x > 0 and x % 2 == 0 }
odd_pos = data.select { |x| x > 0 and x % 2 == 1 }
odd_neg = data.select { |x| x < 0 and x % 2 == 1 }

if odd_pos.length > 0
    puts (even.reduce(0, :+) + odd_pos.reduce(:+))
else
    puts (even.reduce(0, :+) + odd_neg.max)
end

gets
res, aa = 0, []
"-2 2 -3 1".split.map(&:to_i).each do |a|
  if a & 1 == 1
    aa.push(a)
  elsif a > 0
    res += a
  end
end
aa.sort!
aa.shift if aa.length & 1 == 0
res += aa.pop
until aa.empty? do
  a = aa.pop + aa.pop
  break if a <= 0
  res += a
end
p res


m = gets.to_i

q = gets.split(" ").collect{|x| x.to_i}
n = gets.to_i
a = gets.split(" ").collect{|x| x.to_i}

result = 0

a.sort! { |a, b| b <=> a }
qm = q.min

t = qm
k = 0

a.each_index { |i|
	if t > 0
		result += a[i]
		t -= 1
		k = 2
	elsif k > 0
		k -= 1
		if k == 0
			t= qm
		end
	end
}

puts result

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

pairs=[nil]*10
10.times {|i| pairs[i]=Pair.new(0,0)}

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

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

pair=Pair.new(0,0)
m=gets.to_i
min=gets.split.map(&:to_i).min
n=gets.to_i

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

class Pair
    attr_reader :pos,:val

    def initialize(pos, val)
        @pos=pos
        @val=val
    end

    def <=>(other)
        val<=>other.val
    end
end

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

a=gets.split.map(&:to_i).sort {|a,b| b<=>a}

i=0
ans=0
while i<n
  min.times {
      break if i==n
      ans+=a[i]
      i+=1
  }

  i+=2
end

puts ans

BEGIN{
	def gint()
		return gets.split.map(&:to_i)
	end
	def main()
		m = gint
		p = gint
		w = p.min
		n = gint
		a = gint
		a.sort!
		sum = 0
		n = a.length - 1
		i = n
		#print a
		#puts
#		puts "START_ALL"
		while i >= 0 do
#			puts "START"
#			puts i
			w.times do |u|
#				puts u
				sum += a[i - u] if i - u >= 0
			end
			i -= w
			i -= 2
		end
#			puts "ENDS"
		puts sum
	end
	Test_case = 1
	Test_case.times do
		main()
	end
}

def run
  lines = ARGF.readlines

  m = lines.shift.chomp.to_i
  q = lines.shift.chomp.split(" ").map {|x| x.to_i }
  n = lines.shift.chomp.to_i
  a = lines.shift.chomp.split(" ").map {|x| x.to_i }

  a.sort_by! { |x| -x }
  q.sort!

  ans = 0
  a.each_slice(q.first + 2) do |items|
    ans += items[0, q.first].reduce(&:+)
  end

  puts ans
end

run if $0 == __FILE__

def run
  lines = ARGF.readlines

  m = lines.shift.chomp.to_i
  q = lines.shift.chomp.split(" ").map {|x| x.to_i }
  n = lines.shift.chomp.to_i
  a = lines.shift.chomp.split(" ").map {|x| x.to_i }

  a.sort_by! { |x| -x }
  costs = []

  sum = 0
  a.length.times do |i|
    sum += a[i]
    costs[i] = sum
  end
  costs.unshift(0)

  a.length.times do |i|
    q.each do |item|
      if item <= (a.length - i)
        sum = costs[i]

        item.times do |c|
          sum += a[i + c]
        end

        costs[i + item + 0] = sum if costs[i + item + 0] and costs[i + item + 0] > sum
        costs[i + item + 1] = sum if costs[i + item + 1] and costs[i + item + 1] > sum
        costs[i + item + 2] = sum if costs[i + item + 2] and costs[i + item + 2] > sum
      end
    end
  end

  puts costs[a.length]
end

run if $0 == __FILE__


require 'mathn'

MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
$diff[0] = 2
$diff[1] = 1

prev = MAX
MAX.downto(2) do |i|
  if flag[i]
    prev = i
    $diff[i] = 0
  else
    $diff[i] = prev - i
  end
end

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

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  min = 1 << 30
  m.times do |i|
    sum = 0
    n.times do |j|
      sum += $diff[ary[i][j]]
    end

    min = [min, sum].min
  end

  n.times do |i|
    sum = 0
    m.times do|j|
      sum += $diff[ary[j][i]]
    end

    min = [min, sum].min
  end

  puts min
end

run if $0 == __FILE__

#!/usr/bin/ruby1.9

def eratosthenes(n)
	primes = []
	sieve = (0..n).collect {|x| x}
	start = 2
	while true
		while sieve[start] == 0
			return primes if start == n
			start += 1
		end
		primes.push(start)
		pos = 2*start
		while pos <= n
			sieve[pos] = 0
			pos += start
		end
		sieve[start] = 0
	end
end

primes = eratosthenes(101*1000)
up = Array.new(100*1000+1)
prime_ix = 0
prime = primes[prime_ix]
up.length.times do |i|
	if i <= prime
		up[i] = prime
	else
		prime_ix += 1
		prime = up[i] = primes[prime_ix]
	end
end

r_num, c_num = STDIN.readline.split.collect {|s| s.to_i}
r_totals = Array.new(r_num, 0)
c_totals = Array.new(c_num, 0)

r_num.times do |r|
	row = STDIN.readline.split.collect {|s| s.to_i}
	c_num.times do |c|
		x = row[c]
		r_totals[r] += up[x]-x
		c_totals[c] += up[x]-x
	end
end

puts [r_totals.min, c_totals.min].min

require 'mathn'
MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
prev = MAX
MAX.downto(0) do |i|
  prev = i if flag[i]
  $diff[i] = prev - i
end

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

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  list = []
  list += ary.map           { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  list += ary.transpose.map { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  puts list.min
end

run if $0 == __FILE__

require 'mathn'

MAX = 10 ** 5 + 10

flag = Array.new(MAX, true)
flag[0] = false
flag[1] = false
2.upto(Math::sqrt(MAX)) do |i|
  if flag[i]
    (2 * i).upto(MAX) do |j|
      flag[j] = false if j % i == 0
    end
  end
end

$diff = Array.new(MAX, 0)
prev = MAX
MAX.downto(0) do |i|
  if flag[i]
    prev = i
    $diff[i] = 0
  else
    $diff[i] = prev - i
  end
end

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

  ary = []
  ARGF.readlines.each do |line|
    ary << line.split.map(&:to_i)
  end

  list = []
  list += ary.map           { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  list += ary.transpose.map { |x| x.reduce(0) { |sum, y| sum + $diff[y] } }
  puts list.min
end

run if $0 == __FILE__

require 'prime'

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

k = []
n.times do |j|
	k[j] = gets.split(' ').collect!{|i| i.to_i}
end

min = 100000
column = Array.new(m, 0)

arr = []
pr = []
Prime.each(100010) do |prime|
  pr << prime
end
# p = pr[0]
i = 0
(1..100000).each do |y|
	i += 1 if y > pr[i]
	arr[y] = pr[i]
end

n.times do |i|
	row = 0
	m.times do |j|
		# x = 0
		# y = k[i][j]
		# while !y.prime?
		# 	x += 1
		# 	y += 1
		# end
		x = arr[k[i][j]] - k[i][j]
		row += x
		column[j] += x
	end
	min = row if row < min
end

column.each do |x|
	min = x if x < min
end

p min

# -*- encoding: utf-8 -*-
require 'prime'

n, m = gets.chomp.split(" ").map{ |e| e.to_i }
matrix = []
n.times do
  matrix << gets.chomp.split(" ").map{ |e| e.to_i }
end
primes = Prime.each(100000 + 1000).to_a
min = 100000 * [n, m].max

memo = []
idx = 0
for i in 0 .. 100000 do
  if not i <= primes[idx]
    idx += 1
  end
  memo << primes[idx]
end

matrix.concat matrix.transpose

for i in 0 .. (n + m - 1) do
  col = matrix[i]

  num = 0
  col.each do |n|
    num += memo[n] - n
  end
  min = [min, num].min
end

puts min

# -*- encoding: utf-8 -*-
require 'prime'

class Array
  def binary_search(val, left = 0, right = nil)
    right = self.size - 1 unless right
    mid = (left + right) / 2

    return nil if left > right

    a = (mid > 0) ? self[mid - 1] : 0
    if val < self[mid] and val > a
      return self[mid]
    elsif val > self[mid]
      binary_search(val, mid + 1, right)
    else
      binary_search(val, left, mid - 1)
    end
  end
end

n, m = gets.chomp.split(" ").map{ |e| e.to_i }
matrix = []
n.times do
  matrix << gets.chomp.split(" ").map{ |e| e.to_i }
end
# 行列を入れ替えたものを結合
matrix.concat matrix.transpose
primes = Prime.each(100000).to_a
min = 100000 * [n, m].max
memo = {}

for i in 0 .. (n + m - 1) do
  col = matrix[i]

  num = 0
  col.each do |n|
    if not primes.include? n
      if memo.include? n
        num += memo[n]
      else
        tmp = primes.binary_search(n)
        memo[n] = tmp

        num += tmp - n
      end
    end
  end
  min = [min, num].min
end

puts min


def is_alph(s)
  s = s.chars
  cur = ('a'.ord + s.size - 1).chr

  while !s.empty? && cur >= 'a'
    if s.first == cur
      s = s[1..]
    elsif s.last == cur
      s = s[0..-2]
    else
      break
    end
    cur = (cur.ord - 1).chr
  end

  s.empty? && (cur.ord + 1).chr == 'a'
end

gets.to_i.times {
  s = gets.strip
  puts(is_alph(s) ? 'YES' : 'NO')
}

ALL_CHARS = 'abcdefghijklmnopqrstuvwxyz'.freeze

def solve(inp)
  orig_size = inp.size
  ptr = 0
  chars = ALL_CHARS[0...orig_size].reverse

  while inp.size > 0 do
    return false unless inp[0] == chars[ptr] || inp[-1] == chars[ptr]
    inp = inp.sub(chars[ptr], '')
    ptr += 1
  end

  orig_size == ptr
end

t = gets.chomp.to_i
t.times do
  inp = gets.chomp
  solve(inp) ? puts("YES\n") : puts("NO\n")
end


t = gets.to_i

t.times do
  n = gets.to_i
  arr = gets.split(' ').map(&:to_i)

  puts arr[0] == arr.sort[0] ? 'YES' : 'NO'
end

gets.to_i.times do
    _=gets.chomp.to_i
    arr=gets.chomp.split.map(&:to_i)
    if arr[0]==1
        puts "Yes"
    else
        puts "No"
    end
end


gets.to_i.times do
  n, q = gets.split.map(&:to_i)
  as = [0] + gets.split.map(&:to_i).sort_by { -_1 }
  (1...as.size).each { |i| as[i] += as[i - 1] }

  q.times do
    query = gets.to_i

    l = 0
    r = as.size
    while l + 1 < r
      m = (l + r) / 2
      if as[m] >= query
        r = m
      else
        l = m
      end
    end

    p -1 if r >  n
    p  r if r <= n
  end
end

gets.to_i.times do
  n, q = gets.split.map(&:to_i)
  as = gets.split.map(&:to_i).sort.reverse
  sums = [0]
  as.each { |a| sums << sums.last + a }
  q.times do
    x = gets.to_i
    p sums.bsearch_index { |s| s >= x } || -1
  end
end

def solve
  n, q = gli
  b = gli.sort.reverse
  (1...n).each { |i| b[i] += b[i - 1] }
  q.times do
    d = gi
    z = b.bsearch_index { |x| x >= d }
    if z
      puts z + 1
    else
      puts(-1)
    end
  end
end

MOD = 10**9 + 7
def gs = gets.chomp
def gi = gets.to_i
def gli = gets.split.map(&:to_i)
def cyesno(x) = x ? :Yes : :No
def uyesno(x) = x ? :YES : :NO

gets.to_i.times { solve }

main = -> {
  t = int
  t.times do
      n, q = ints
      a = ints
      a.sort!
      a.reverse!
      sum = [0]
      a.each do |x|
          sum << sum[-1] + x
      end
      q.times do
          x = int
          puts sum.bsearch_index { |s| s >= x } || -1
      end
  end
}

DEBUG = true
MOD = 10**9+7
$yesno = %w(No Yes)
YesNo = %w(No Yes)
YESNO = %w(NO YES)
INF = 10**18

require "set"
require "prime"

def int; gets.to_s.to_i end
def ints; gets.to_s.split.map { |s| s.to_i } end
def int1s; gets.to_s.split.map { |s| s.to_i - 1 } end
def float; gets.to_s.to_f end
def floats; gets.to_s.split.map { |s| s.to_f } end
def array_of(&convert); gets.to_s.split.map(&convert) end
def string; gets.to_s.chomp end
def strings; gets.to_s.split end
def rep(n, &b); Array.new(n, &b) end
def yes; puts $yesno[1] end
def no; puts $yesno[0] end
def yesno t; puts $yesno[t] end
def YesNo t; puts YesNo[t] end
def YESNO t; puts YESNO[t] end
def zip(xs, *yss); Enumerator.new { |y| xs.zip(*yss) { |a| y.yield(*a) } } end
def max(*xs, &block); block_given? ? xs.max_by(&block) : xs.max end
def min(*xs, &block); block_given? ? xs.min_by(&block) : xs.min end
def minmax(*xs, &block); block_given? ? xs.minmax_by(&block) : xs.minmax end
def gcd(*xs); xs.inject(0, :gcd) end
def matrix(h, w, fill=nil, &block); return Array.new(h) { Array.new(w, &block) } if block_given?; Array.new(h) { [fill] * w } end
def debug(x = nil); STDERR.puts (block_given? ? yield(x) : x).inspect if DEBUG; x end
def debug_grid(grid, width = 1); grid.each { |row| STDERR.puts row.map { |x| x.inspect.ljust(width) }.join("") } if DEBUG; grid end
def if_debug; yield if DEBUG end

module Boolean
  def coerce(other); [other, to_i] end
  def +@; to_i end
  def to_int; to_i end
  def *(other); to_i * other end
end

class TrueClass
  include Boolean
  def to_i; 1 end
end

class FalseClass
  include Boolean
  def to_i; 0 end
end

class Integer
  def div_ceil(y); (self + y - 1) / y end
  def mod_inv(mod = MOD); pow(mod-2, mod) end
  def mod_div(y, mod = MOD); self * y.mod_inv(mod) % mod end
  def mod_nCr(r, mod = MOD); x = y = 1; (1..r).each { |i| x = x * (self + 1 - i) % mod; y = y * i % mod }; x.mod_div(y, mod); end
  def factorial(mod = MOD); (2..self).inject(1) { |f, x| f * x % mod } end
  def popcount; x = self; c = 0; while x > 0; c += 1 if x & 1 == 1; x >>= 1 end; c end #TODO: faster
  def bitbrute(&block); (1<<self).times(&block) end
  def nCr(r); x = 1; (1..r).each { |i| x *= self + 1 - i; x /= i }; x; end
  def each_divisor; return Enumerator.new { |y| each_divisor { |k| y << k } } unless block_given?; k = 1; while k * k < self; if self % k == 0; yield k; yield self / k end; k += 1; end; yield k if k * k == self end
  def divisors; each_divisor.to_a end
end

class Range
  def end_open; exclude_end? ? self.end : self.end + 1 end
  def end_close; exclude_end? ? self.end - 1 : self.end end
  def upper_bound; ac, wa = self.begin, self.end_open; while wa - ac > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def lower_bound; ac, wa = self.end_open, self.begin; while ac - wa > 1; if yield((wj = (ac + wa) / 2)); ac = wj else wa = wj end; end; yield(ac) ? ac : nil end
  def shakutori(r2, &pred); Enumerator.new { |y| j, r = r2.begin, r2.end_open; each { |i| j += 1 while j + 1 < r and pred[i, j+1]; y.yield(i, j) } }; end
  def widest(&block); Enumerator.new { |y| j, n = self.begin, self.end_open; each { |i| j += 1 while j < n and block[i, j]; y.yield(i, j) if block[i, j] } } end
end

class Array
  def power(&block); (0 ... 1 << size).each(&block) end
  def sorted_merge(other); a = []; i = j = 0; n, m = size, other.size; if j < m and other[j] < self[i]; a << other[j]; j += 1 else; a << self[i]; i += 1 end while i < n; a.push(*other[j..-1]) if j < m; a end
  def upper_bound; ac, wa = 0, size; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def lower_bound; ac, wa = size, 0; while wa - ac > 1; if yield(self[(wj = (ac + wa) / 2)]); ac = wj else; wa = wj end; end; ac end
  def cum(*xs, &op); a = []; a << xs[0] if xs.size > 0; a << x = self[0]; (1...size).each { |i| a << x = op[x, self[i]] }; a end
  def cumdiff(range); self[range.end_open] - self[range.begin]; end
  def compress(kinds = uniq.sort!); map { |x| kinds.bsearch_index { _1 >= x } }; end
end

module Enumerable
  def sorted_uniq; x = nil; filter { |y| c = x === y; x = y; !c } end
  def cumsum; ys = [0]; each { |x| ys << x + ys[-1] }; ys end
end

main[]