Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.

The first line contains an integer n (1 ≤ n ≤ 100): number of names. Each of the following n lines contain one string namei (1 ≤ |namei| ≤ 100), the i-th name. Each name contains only lowercase Latin letters. All names are different.

If there exists such order of letters that the given names are sorted lexicographically, output any such order as a permutation of characters 'a'–'z' (i. e. first output the first letter of the modified alphabet, then the second, and so on). Otherwise output a single word "Impossible" (without quotes).

10
tourist
petr
wjmzbmr
yeputons
vepifanov
scottwu
oooooooooooooooo
subscriber
rowdark
tankengineer

10
petr
egor
endagorion
feferivan
ilovetanyaromanova
kostka
dmitriyh
maratsnowbear
bredorjaguarturnik
cgyforever

7
car
care
careful
carefully
becarefuldontforgetsomething
otherwiseyouwillbehacked
goodluck

bcdefghijklmnopqrsatuvwxyz Impossible aghjlnopefikdmbcqrstuvwxyz acbdefhijklmnogpqrstuvwxyz

#!/usr/bin/env ruby
require 'tsort'
class Hash
	include TSort
	alias tsort_each_node each_key
	def tsort_each_child(node, &block)
		fetch(node).each(&block)
	end
end
A=gets.to_i.times.map{gets.chomp.chars.to_a}
h={}
A.combination(2){|x,y|
	if [x.size,y.size].min.times{|i|
		if x[i]!=y[i]
			h[x[i]]||=[]
			h[y[i]]||=[]
			h[y[i]]<<x[i]
			break
		end
	} && x.size>y.size
		puts :Impossible
		exit
	end
}
r=([*'a'..'z']-h.keys+h.tsort)*'' rescue 'Impossible'
puts r

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		if !edgeExists?(startVertex, endVertex)
			@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
			# puts "#{startVertex} #{endVertex}"
		end
	end

	def edgeExists?(startVertex, endVertex)
		@vertexSet[startVertex].children.include?(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp

(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible\n"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  # puts "Processing letter: #{letter}"
  # p next_vert
  if next_vert.nil?
    # puts letter
    color[letter] = 'black'
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      # puts "#{letter} color is grey and it means we have a cycle"
      return "Impossible"
    elsif color[next_vert.element] == 'white'
      # puts "#{next_vert.element}'s color is white"
      new_letter = dfs(graph, next_vert.element, color)
      # puts new_letter
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})
alphabet = []
(n - 1).times do |i|
  length = names[i].length
  length.times do |j|
    if j >= names[i+1].length
      alphabet = "Impossible"
      break
    end
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

# letters.print_edges

color = {}
("a".."z").each do |letter|
  color[letter] = 'white'
end
# puts "All the letters in the graph: #{letters.vertices.keys}"
# alphabet = []
if alphabet != "Impossible"
  letters.vertices.each_key do |letter|
    if color[letter] == 'white'
      ordered_letters = dfs(letters, letter, color)
      if ordered_letters == "Impossible"
        alphabet = "Impossible"
        break
      end
      alphabet = ordered_letters + alphabet
    end
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

Point = Struct.new(:char, :color, :children)
chars = Hash[('a'..'z').map{|c| [c, Point.new(c, :white, [])]}]
n = gets.to_i
words = []
n.times do
  words << gets.chomp.chars
end
words.each_cons(2) do |prv,nxt|
  p, n = prv.zip(nxt).drop_while{|p,n| p==n}.first
  if n == nil
    if p == nil
      next
    else
      puts "Impossible"
      exit
    end
  end
  (chars[p].children << chars[n]).uniq!{|v| v.char}
end
def yoba(v,order)
  case v.color
  when :gray
    return false
  when :black
    return true
  end
  v.color = :gray
  v.children.each do |v|
    return false unless yoba(v, order)
  end
  v.color = :black
  order << v.char
  true
end
order = []
chars.values.reverse.each do |v|
  unless yoba(v,order)
    puts "Impossible"
    exit
  end
end
puts order.reverse.join

#!/usr/bin/env ruby
require 'tsort'
class Hash
	include TSort
	alias tsort_each_node each_key
	def tsort_each_child(node, &block)
		fetch(node).each(&block)
	end
end
A=gets.to_i.times.map{gets.chomp.chars.to_a}
h={}
A.combination(2){|x,y|
	[x.size,y.size].min.times{|i|
		if x[i]!=y[i]
			h[x[i]]||=[]
			h[y[i]]||=[]
			h[y[i]]<<x[i]
			break
		end
	}
}
r=([*'a'..'z']-h.keys+h.tsort)*'' rescue 'Impossible'
puts r

#!/usr/bin/env ruby
require 'tsort'
class Hash
	include TSort
	alias tsort_each_node each_key
	def tsort_each_child(node, &block)
		fetch(node).each(&block)
	end
end
A=gets.to_i.times.map{gets.chomp.chars.to_a}
h={}
A.combination(2){|x,y|
	if x.size>y.size && [x.size,y.size].min.times{|i|
		if x[i]!=y[i]
			h[x[i]]||=[]
			h[y[i]]||=[]
			h[y[i]]<<x[i]
			break
		end
	}
		puts :Impossible
		exit
	end
}
r=([*'a'..'z']-h.keys+h.tsort)*'' rescue 'Impossible'
puts r

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible2\n"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
end

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "IMPOSSIBLE"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "IMPOSSIBLE\n"
end

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		if !edgeExists?(startVertex, endVertex)
			@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
		end
	end

	def edgeExists?(startVertex, endVertex)
		@vertexSet[startVertex].children.include?(endVertex)
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
# myFlag = 0
# if n == 100
# 	if str[0] == 'a'
# 		myFlag = 1
# 	end
# end
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible\n"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
b = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
	b.push
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
	# if myFlag == 1
	# 	print "#{a.join("")}\n"
	# end
end

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
end

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible\n"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
end

class Graph
	attr_reader :vertexSet, :edgeSet
	def initialize(numberOfVertices) # adds vertices in a new blank graph by their numbers
		@vertexSet = Array.new()
		(0..(numberOfVertices - 1)).each do |i|
			@vertexSet.push(Vertex.new(i))
		end
	end

	def addEdge(startVertex, endVertex)
		@vertexSet[startVertex].addNbr(@vertexSet[endVertex])
	end

	def printEdges
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def countEdges
		t = 0
		@vertexSet.each do |vertex|
			if (vertex.children.size != 0)
				vertex.children.each do |v|
					t += 1
				end
			end
		end
		t
	end

	def printParentEdges
		@vertexSet.each do |vertex|
			if (vertex.parents.size != 0)
				vertex.parents.each do |v|
					puts "#{vertex.index} #{v.index}"
				end
			end
		end
	end

	def returnSources
		temp = Array.new()
		@vertexSet.each do |vertex|
			if (vertex.parents.size == 0)
				temp.push(vertex)
			end
		end
		return temp
	end

	def returnVertex(index)
		@vertexSet[index]
	end

	def settleThings
		flag = 0
		temp = Vertex.new(-1)
		@vertexSet.each do |vertex|
			if vertex.alone?
				# puts "Gotcha #{vertex.index}!!!"
				if flag == 0
					# puts "Voila"
					temp = vertex
					flag = 1
				else
					# puts "Temp."
					temp.addNbr(vertex)
					temp = vertex
				end
			end
		end
	end

	def DFS(index)
		vertex = returnVertex(index)
		print "#{index}."
		vertex.children.each do |v|
			DFS(v.index)
		end
	end

end

class Vertex
	attr_reader :index, :children, :parents, :color
	def initialize(index)
		@index = index
		@children = Array.new()
		@parents = Array.new()
		@color = 0
	end

	def addNbr(index)
		@children.push(index)
		index.parents.push(self)
	end

	def changeColor(color)
		@color = color
	end

	def alone?
		return ((@parents.size == 0) and (@children.size == 0))
	end
end

class Heap
	attr_accessor :heap_size, :array_rep

	def initialize()
		@array_rep = Array.new()
		@heap_size = 0
	end

	def parent(index)
		(index - 1)/2
	end

	def parentKey(index)
		@array_rep[parent(index)]
	end

	def leftChild(index)
		2*index + 1
	end

	def rightChild(index)
		2*index + 2
	end

	def leftChildKey(index)
		@array_rep[leftChild(index)]
	end

	def rightChildKey(index)
		@array_rep[rightChild(index)]
	end

	def leafNode?(index)
		return index >= @heap_size/2
	end

	def getMin
		@array_rep[0]
	end

	def deleteMin
		@array_rep[@heap_size-1], @array_rep[0] = @array_rep[0], @array_rep[@heap_size-1]
    	@heap_size -= 1
		@array_rep.delete_at(@heap_size)
		self.fixOneError(0)
	end

	def extractMin
		temp = getMin.to_i
		deleteMin
		return temp
	end

	def fixOneError(index)
		return if leafNode?(index) || satisfied?(index)

	    leftChildKey = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
	    rightChildKey = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end

    	smallerChild = if leftChildKey < rightChildKey then leftChild(index) else rightChild(index) end

    	@array_rep[index], @array_rep[smallerChild] = @array_rep[smallerChild], @array_rep[index]

    	fixOneError(smallerChild)
  	end

	def satisfied?(index)
		# puts "\nin , #{index} Verify :"
		# displayStatus
		t1 = if @array_rep[leftChild(index)] != nil then @array_rep[leftChild(index)] else Float::INFINITY end
		t2 = if @array_rep[rightChild(index)] != nil then @array_rep[rightChild(index)] else Float::INFINITY end
		@array_rep[index] <= t1 and @array_rep[index] <= t2
  	end

	def insert(value)
		@array_rep.push(value)
		@heap_size += 1
		index = @heap_size - 1

		while ((!(top?(index))) and (@array_rep[parent(index)] > @array_rep[index]))
			@array_rep[index], @array_rep[parent(index)] = @array_rep[parent(index)], @array_rep[index]
			index = parent(index)
		end
	end

	def top?(index)
		return index == 0
	end

	def displayStatus
		puts "Status :"
		@array_rep.each do |d|
			print "#{d}."
		end
	end
end

def analyse(x, y)
	x = x.each_char.to_a
	y = y.each_char.to_a
	# puts "x: #{x}"
	# puts "y: #{y}"
	t = if x.size > y.size then y.size else x.size end
	(0..(t-1)).each do |i|
		# puts "x: #{x[i]} y: #{y[i].ord}"
		if x[i].ord != y[i].ord
			return [(x[i].ord-97),(y[i].ord-97)]
		end
	end
	if x.size > y.size
		return [-2, -2]
	end
	return -1, -1
end

# code starts here :

myGraph = Graph.new(26)
n = gets.chomp.to_i
str = gets.chomp
myFlag = 0
if n == 100
	if str[0] == 'a'
		myFlag = 1
	end
end
(2..n).each do |j|
	str2 = gets.chomp
	n1, n2 = analyse(str, str2)
	if (n1 == -2)
		puts "Impossible\n"
		exit
	end
	if (n1 != -1)
		myGraph.addEdge(n1, n2)
	end
	str = str2
end

myGraph.settleThings()
# puts "#{myGraph.vertexSet.size - 1} #{myGraph.countEdges}"
# myGraph.printEdges
#
# if ((myGraph.vertexSet.size - 1) < myGraph.countEdges)
# 	puts "IMPOSSIBLE"
# 	exit
# end

myHeap = Heap.new()

sources = myGraph.returnSources()

sources.each do |z|
	myHeap.insert(z.index)
	z.changeColor(1)
end
a = Array.new()
while (myHeap.heap_size != 0)
	currentVertex = myGraph.returnVertex(myHeap.extractMin)
	currentVertex.changeColor(2)
	currentVertex.children.each do |v|
		if (v.parents.all? {|y| y.color == 2 })
			myHeap.insert(v.index)
			v.changeColor(1)
		end
	end
	a.push((currentVertex.index.to_i+97).chr)
end
if a.size == 26
	print "#{a.join("")}\n"
else
	print "Impossible\n"
	if myFlag == 1
		print "#{a.join("")}\n"
	end
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  if next_vert.nil?
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      return "Impossible"
    else
      new_letter = dfs(graph, next_vert.element, color)
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})

(n - 1).times do |i|
  length = [names[i].length, names[i+1].length].min
  length.times do |j|
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

color = {}
letters.vertices.each_key do |letter|
  color[letter] = 'white'
end
alphabet = []
letters.vertices.each_key do |letter|
  if color[letter] == 'white'
    ordered_letters = dfs(letters, letter, color)
    if ordered_letters == "Impossible"
      alphabet = "Impossible"
      break
    end
    alphabet += ordered_letters
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  puts "Processing letter: #{letter}"
  p next_vert
  if next_vert.nil?
    # puts letter
    color[letter] = 'black'
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      puts "#{letter} color is grey and it means we have a cycle"
      return "Impossible"
    elsif color[next_vert.element] == 'white'
      puts "#{next_vert.element}'s color is white"
      new_letter = dfs(graph, next_vert.element, color)
      puts new_letter
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})
alphabet = []
(n - 1).times do |i|
  length = names[i].length
  length.times do |j|
    if j >= names[i+1].length
      alphabet = "Impossible"
      break
    end
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

# letters.print_edges

color = {}
("a".."z").each do |letter|
  color[letter] = 'white'
end
# puts "All the letters in the graph: #{letters.vertices.keys}"
# alphabet = []
if alphabet != "Impossible"
  letters.vertices.each_key do |letter|
    if color[letter] == 'white'
      ordered_letters = dfs(letters, letter, color)
      if ordered_letters == "Impossible"
        alphabet = "Impossible"
        break
      end
      alphabet = ordered_letters + alphabet
    end
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  # puts "Processing letter: #{letter}"
  # p next_vert
  if next_vert.nil?
    # puts letter
    color[letter] = 'black'
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      # puts "#{letter} color is grey and it means we have a cycle"
      return "Impossible"
    elsif color[next_vert.element] == 'white'
      # puts "#{next_vert.element}'s color is white"
      new_letter = dfs(graph, next_vert.element, color)
      # puts new_letter
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})

(n - 1).times do |i|
  length = [names[i].length, names[i+1].length].min
  length.times do |j|
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

# letters.print_edges

color = {}
("a".."z").each do |letter|
  color[letter] = 'white'
end
# puts "All the letters in the graph: #{letters.vertices.keys}"
alphabet = []
letters.vertices.each_key do |letter|
  if color[letter] == 'white'
    ordered_letters = dfs(letters, letter, color)
    if ordered_letters == "Impossible"
      alphabet = "Impossible"
      break
    end
    alphabet = ordered_letters + alphabet
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  # puts "Processing letter: #{letter}"
  # p next_vert
  if next_vert.nil?
    # puts letter
    color[letter] = 'black'
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      # puts "#{letter} color is grey and it means we have a cycle"
      return "Impossible"
    elsif color[next_vert.element] == 'white'
      # puts "#{next_vert.element}'s color is white"
      new_letter = dfs(graph, next_vert.element, color)
      # puts new_letter
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})

(n - 1).times do |i|
  length = [names[i].length, names[i+1].length].min
  length.times do |j|
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

# letters.print_edges

color = {}
("a".."z").each do |letter|
  color[letter] = 'white'
end
# puts "All the letters in the graph: #{letters.vertices.keys}"
alphabet = []
letters.vertices.each_key do |letter|
  if color[letter] == 'white'
    ordered_letters = dfs(letters, letter, color)
    if ordered_letters == "Impossible"
      alphabet = "Impossible"
      break
    end
    alphabet += ordered_letters
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, color)
  color[letter] = 'grey'
  next_vert = graph.vertices[letter]
  # puts "Processing letter: #{letter}"
  # p next_vert
  if next_vert.nil?
    # puts letter
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if color[next_vert.element] == 'grey'
      return "Impossible"
    elsif color[next_vert.element] == 'white'
      # puts "#{next_vert.element}'s color is white"
      new_letter = dfs(graph, next_vert.element, color)
      # puts new_letter
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  color[letter] = 'black'
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})

(n - 1).times do |i|
  length = [names[i].length, names[i+1].length].min
  length.times do |j|
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

# letters.print_edges

color = {}
("a".."z").each do |letter|
  color[letter] = 'white'
end
# puts "All the letters in the graph: #{letters.vertices.keys}"
alphabet = []
letters.vertices.each_key do |letter|
  if color[letter] == 'white'
    ordered_letters = dfs(letters, letter, color)
    if ordered_letters == "Impossible"
      alphabet = "Impossible"
      break
    end
    alphabet += ordered_letters
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

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(letter1, letter2)
    if vertices[letter1].nil? then
      vertices[letter1] = List.new(letter2, nil)
    else
      vertices[letter1] = List.new(letter2, vertices[letter1])
    end
  end

  # def add_vertex(letter)
  #   vertices[letter] = "" if vertices[letter].nil?
  # end

  def print_edges
    vertices.each do |letter, vertex|
      # next if vertex == ""
      while !vertex.nil? do
        puts "edge #{letter} - #{vertex.element}"
        vertex = vertex.next_elem
      end
    end
  end

  # def print_verteces
  #   puts vertices.keys.join(" ")
  # end
end

def dfs(graph, letter, marked)
  marked[letter] = true
  next_vert = graph.vertices[letter]
  if next_vert.nil?
    return [letter]
  end
  alphabet = []
  while !next_vert.nil? do
    if marked[next_vert.element]
      return "Impossible"
    else
      new_letter = dfs(graph, next_vert.element, marked)
      if new_letter == "Impossible"
        return "Impossible"
      else
        alphabet = new_letter + alphabet
      end
    end
    next_vert = next_vert.next_elem
  end
  return [letter] + alphabet
end

def permutation(sorted_letters)
  sorted_letters | ("a".."z").to_a
end

names = []
n = gets.strip.to_i
n.times{|i| names.push(gets.strip)}
letters = Graph.new({})

(n - 1).times do |i|
  length = [names[i].length, names[i+1].length].min
  length.times do |j|
    if names[i][j] != names[i+1][j]
      letters.add_edge(names[i][j], names[i+1][j])
      break
    end
  end
end

marked = {}
letters.vertices.each_key do |letter|
  marked[letter] = false
end
alphabet = []
letters.vertices.each_key do |letter|
  if !marked[letter]
    ordered_letters = dfs(letters, letter, marked)
    if ordered_letters == "Impossible"
      alphabet = "Impossible"
      break
    end
    alphabet += ordered_letters
  end
end
if alphabet == "Impossible"
  puts alphabet
else
  puts permutation(alphabet).join
end

Point = Struct.new(:char, :color, :children)
chars = Hash[('a'..'z').map{|c| [c, Point.new(c, :white, [])]}]
n = gets.to_i
words = []
n.times do
  words << gets.chomp.chars
end
words.each_cons(2) do |prv,nxt|
  p, n = prv.zip(nxt).drop_while{|p,n| p==n}.first
  if n == nil
    if n == nil
      next
    else
      puts "Impossible"
      exit
    end
  end
  (chars[p].children << chars[n]).uniq!{|v| v.char}
end
def yoba(v,order)
  case v.color
  when :gray
    return false
  when :black
    return true
  end
  v.color = :gray
  v.children.each do |v|
    return false unless yoba(v, order)
  end
  v.color = :black
  order << v.char
  true
end
order = []
chars.values.reverse.each do |v|
  unless yoba(v,order)
    puts "Impossible"
    exit
  end
end
puts order.reverse.join


You are given a binary string of length $$$n$$$ (i. e. a string consisting of $$$n$$$ characters '0' and '1').In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than $$$k$$$ moves? It is possible that you do not perform any moves at all.Note that you can swap the same pair of adjacent characters with indices $$$i$$$ and $$$i+1$$$ arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.You have to answer $$$q$$$ independent test cases.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^6, 1 \le k \le n^2$$$) — the length of the string and the number of moves you can perform. The second line of the test case contains one string consisting of $$$n$$$ characters '0' and '1'. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^6$$$ ($$$\sum n \le 10^6$$$).

For each test case, print the answer on it: the lexicographically minimum possible string of length $$$n$$$ you can obtain from the given one if you can perform no more than $$$k$$$ moves.

NoteIn the first example, you can change the string as follows: $$$1\underline{10}11010 \rightarrow \underline{10}111010 \rightarrow 0111\underline{10}10 \rightarrow 011\underline{10}110 \rightarrow 01\underline{10}1110 \rightarrow 01011110$$$. In the third example, there are enough operations to make the string sorted.

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

q = inp[0]
indata = []
(q*2).times do
  indata << gets.chomp
end
(q).times do |di|
  n, k = indata[di*2].split.map(&:to_i)
  t = indata[di*2+1]
  head = 0
  nk = k
  n.times do |i|
    next unless t[i] == "0"
    sa = (i-head)
    if(sa < nk)
      t[head], t[i] = t[i], t[head]
      head += 1
      nk -= sa
    else
      t[i - nk], t[i] = t[i], t[i - nk]
      nk == 0
      break
    end
  end
  puts t
end


Ashish and Vivek play a game on a matrix consisting of $$$n$$$ rows and $$$m$$$ columns, where they take turns claiming cells. Unclaimed cells are represented by $$$0$$$, while claimed cells are represented by $$$1$$$. The initial state of the matrix is given. There can be some claimed cells in the initial state.In each turn, a player must claim a cell. A cell may be claimed if it is unclaimed and does not share a row or column with any other already claimed cells. When a player is unable to make a move, he loses and the game ends.If Ashish and Vivek take turns to move and Ashish goes first, determine the winner of the game if both of them are playing optimally.Optimal play between two players means that both players choose the best possible strategy to achieve the best possible outcome for themselves.

The first line consists of a single integer $$$t$$$ $$$(1 \le t \le 50)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case consists of two space-separated integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the matrix. The following $$$n$$$ lines consist of $$$m$$$ integers each, the $$$j$$$-th integer on the $$$i$$$-th line denoting $$$a_{i,j}$$$ $$$(a_{i,j} \in \{0, 1\})$$$.

For each test case if Ashish wins the game print "Ashish" otherwise print "Vivek" (without quotes).

NoteFor the first case: One possible scenario could be: Ashish claims cell $$$(1, 1)$$$, Vivek then claims cell $$$(2, 2)$$$. Ashish can neither claim cell $$$(1, 2)$$$, nor cell $$$(2, 1)$$$ as cells $$$(1, 1)$$$ and $$$(2, 2)$$$ are already claimed. Thus Ashish loses. It can be shown that no matter what Ashish plays in this case, Vivek will win. For the second case: Ashish claims cell $$$(1, 1)$$$, the only cell that can be claimed in the first move. After that Vivek has no moves left.For the third case: Ashish cannot make a move, so Vivek wins.For the fourth case: If Ashish claims cell $$$(2, 3)$$$, Vivek will have no moves left.

tests = gets.to_i
tests.times do
	rows, columns = gets.split(' ')
	rows = rows.to_i
	columns = columns.to_i
	table = Array.new(rows){Array.new(columns)}
	cnt_rows = Array.new(rows, 0)
	cnt_columns = Array.new(columns, 0)
	rows.times do
		|row|
		line = gets.split(' ')
		columns.times do
			|column|
			table[row][column] = line[column].to_i
			cnt_rows[row] += table[row][column]
			cnt_columns[column] += table[row][column]
		end
	end
	cnt_missing_rows = 0
	cnt_missing_columns = 0
	rows.times do
		|idx|
		if cnt_rows[idx] == 0
			cnt_missing_rows += 1
		end
	end

	columns.times do
		|idx|
		if cnt_columns[idx] == 0
			cnt_missing_columns += 1
		end
	end
	res = [cnt_missing_rows, cnt_missing_columns].min
	if res%2 == 0
		puts "Vivek"
	else
		puts "Ashish"
	end
end

tasks_numbers = gets.chomp
allowed_lines = []
(1..tasks_numbers.to_i).each do
	rows_cols = gets.chomp
	rows, cols = rows_cols.split(" ").map{|e| e.to_i}
	all_pairs = rows + cols
	allowed_cols = (1..cols).to_a
	allowed_rows_qty = rows
	(1..rows).each do
		index = 0
		isset_1 = false
		values = gets.chomp
		values.split(" ").each do |value|
			index += 1
			if value == '1'
				allowed_cols.delete(index)
				isset_1 = true
			end
		end
		allowed_rows_qty -= 1 if isset_1
	end
	allowed_lines.push [allowed_rows_qty, allowed_cols.length].min
end

allowed_lines.each do |allowed_line|
	if allowed_line == 0
		puts 'Vivek'
	else
		if allowed_line % 2 > 0
			puts 'Ashish'
		else
			puts 'Vivek'
		end
	end
end

tasks_numbers = gets.chomp
allowed_lines = []
(1..tasks_numbers.to_i).each do
	rows_cols = gets.chomp
	rows, cols = rows_cols.split(" ").map{|e| e.to_i}
	all_pairs = rows + cols
	allowed_cols = (1..cols).to_a
	allowed_rows_qty = rows
	(1..rows).each do
		index = 0
		isset_1 = false
		values = gets.chomp
		values.split(" ").each do |value|
			index += 1
			if value == '1'
				allowed_cols.delete(index)
				isset_1 = true
			end
		end
		allowed_rows_qty -= 1 if isset_1
	end
	allowed_lines.push(allowed_rows_qty + allowed_cols.length)
end

allowed_lines.each do |allowed_line|
	if allowed_line < 2
		puts 'Vivek'
	else
		allowed_line -= 1 if allowed_line % 2 > 0
		allowed_line = allowed_line / 2
		if allowed_line % 2 > 0
			puts 'Ashish'
		else
			puts 'Vivek'
		end
	end
end


Vasya owns a cornfield which can be defined with two integers $$$n$$$ and $$$d$$$. The cornfield can be represented as rectangle with vertices having Cartesian coordinates $$$(0, d), (d, 0), (n, n - d)$$$ and $$$(n - d, n)$$$.    An example of a cornfield with $$$n = 7$$$ and $$$d = 2$$$. Vasya also knows that there are $$$m$$$ grasshoppers near the field (maybe even inside it). The $$$i$$$-th grasshopper is at the point $$$(x_i, y_i)$$$. Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.Help Vasya! For each grasshopper determine if it is inside the field (including the border).

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1 \le d < n \le 100$$$). The second line contains a single integer $$$m$$$ ($$$1 \le m \le 100$$$) — the number of grasshoppers. The $$$i$$$-th of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$0 \le x_i, y_i \le n$$$) — position of the $$$i$$$-th grasshopper.

Print $$$m$$$ lines. The $$$i$$$-th line should contain "YES" if the position of the $$$i$$$-th grasshopper lies inside or on the border of the cornfield. Otherwise the $$$i$$$-th line should contain "NO". You can print each letter in any case (upper or lower).

NoteThe cornfield from the first example is pictured above. Grasshoppers with indices $$$1$$$ (coordinates $$$(2, 4)$$$) and $$$4$$$ (coordinates $$$(4, 5)$$$) are inside the cornfield.The cornfield from the second example is pictured below. Grasshoppers with indices $$$1$$$ (coordinates $$$(4, 4)$$$), $$$3$$$ (coordinates $$$(8, 1)$$$) and $$$4$$$ (coordinates $$$(6, 1)$$$) are inside the cornfield.

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

hsh = {}

y1 = d
0.upto(n-d).each do |x1|
  y = y1
  x = x1
  (d+1).times do
    hsh["#{x},#{y}"]=true
    y -= 1
    x += 1
  end
  y1 += 1
end

y1 = d
1.upto(n-d).each do |x1|
  y = y1
  x = x1
  d.times do
    hsh["#{x},#{y}"]=true
    y -= 1
    x += 1
  end
  y1 += 1
end

m = gets.to_i
m.times do
  x,y=gets.strip.split.map(&:to_i)
  puts (hsh["#{x},#{y}"] ? "YES" : "NO")
end

n, d = gets.split.map &:to_i
nQ = gets.to_i
nQ.times do
  x, y = gets.split.map &:to_i
  f = true
  f &= x+y >= d
  f &=  (n-x)+(n-y)>=d
  f &= x+(n-y)>=n-d
  f &= (n-x)+y>=n-d
  puts f ? "YES" : "NO"
end


The legend of the foundation of Vectorland talks of two integers $$$x$$$ and $$$y$$$. Centuries ago, the array king placed two markers at points $$$|x|$$$ and $$$|y|$$$ on the number line and conquered all the land in between (including the endpoints), which he declared to be Arrayland. Many years later, the vector king placed markers at points $$$|x - y|$$$ and $$$|x + y|$$$ and conquered all the land in between (including the endpoints), which he declared to be Vectorland. He did so in such a way that the land of Arrayland was completely inside (including the endpoints) the land of Vectorland.Here $$$|z|$$$ denotes the absolute value of $$$z$$$.Now, Jose is stuck on a question of his history exam: "What are the values of $$$x$$$ and $$$y$$$?" Jose doesn't know the answer, but he believes he has narrowed the possible answers down to $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. Now, he wants to know the number of unordered pairs formed by two different elements from these $$$n$$$ integers such that the legend could be true if $$$x$$$ and $$$y$$$ were equal to these two values. Note that it is possible that Jose is wrong, and that no pairs could possibly make the legend true.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$)  — the number of choices. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the choices Jose is considering.

Print a single integer number — the number of unordered pairs $$$\{x, y\}$$$ formed by different numbers from Jose's choices that could make the legend true.

NoteConsider the first sample. For the pair $$$\{2, 5\}$$$, the situation looks as follows, with the Arrayland markers at $$$|2| = 2$$$ and $$$|5| = 5$$$, while the Vectorland markers are located at $$$|2 - 5| = 3$$$ and $$$|2 + 5| = 7$$$:  The legend is not true in this case, because the interval $$$[2, 3]$$$ is not conquered by Vectorland. For the pair $$$\{5, -3\}$$$ the situation looks as follows, with Arrayland consisting of the interval $$$[3, 5]$$$ and Vectorland consisting of the interval $$$[2, 8]$$$:  As Vectorland completely contains Arrayland, the legend is true. It can also be shown that the legend is true for the pair $$$\{2, -3\}$$$, for a total of two pairs.In the second sample, the only pair is $$$\{3, 6\}$$$, and the situation looks as follows:  Note that even though Arrayland and Vectorland share $$$3$$$ as endpoint, we still consider Arrayland to be completely inside of Vectorland.

def bsearch(arr,t)
  ok,ng = 0,arr.length
  while (ng - ok).abs > 1
    mid = (ok+ng)/2
    if arr[mid] <= t
      ok = mid
    else
      ng = mid
    end
  end
  return ok
end

n = gets.to_i
a = gets.split.map{|t|t.to_i.abs}.sort
ans = 0
n.times do |i|
  x = bsearch(a,a[i]*2)
  ans += x-i if x > i
  #p [i,a[i],x-i]
end
p ans


Fox Ciel is playing a card game with her friend Jiro.Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.Now is Ciel's battle phase, Ciel can do the following operation many times:  Choose one of her cards X. This card mustn't be chosen before.  If Jiro has no alive cards at that moment, he gets the damage equal to (X's strength). Otherwise, Ciel needs to choose one Jiro's alive card Y, then:   If Y's position is Attack, then (X's strength)  ≥  (Y's strength) must hold. After this attack, card Y dies, and Jiro gets the damage equal to (X's strength) - (Y's strength).  If Y's position is Defense, then (X's strength)  >  (Y's strength) must hold. After this attack, card Y dies, but Jiro gets no damage.  Ciel can end her battle phase at any moment (so, she can use not all her cards). Help the Fox to calculate the maximal sum of damage Jiro can get.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of cards Jiro and Ciel have. Each of the next n lines contains a string position and an integer strength (0 ≤ strength ≤ 8000) — the position and strength of Jiro's current card. Position is the string "ATK" for attack, and the string "DEF" for defense. Each of the next m lines contains an integer strength (0 ≤ strength ≤ 8000) — the strength of Ciel's current card.

Output an integer: the maximal damage Jiro can get.

NoteIn the first test case, Ciel has 3 cards with same strength. The best strategy is as follows. First she uses one of these 3 cards to attack "ATK 2000" card first, this attack destroys that card and Jiro gets 2500 - 2000 = 500 damage. Then she uses the second card to destroy the "DEF 1700" card. Jiro doesn't get damage that time. Now Jiro has no cards so she can use the third card to attack and Jiro gets 2500 damage. So the answer is 500 + 2500 = 3000.In the second test case, she should use the "1001" card to attack the "ATK 100" card, then use the "101" card to attack the "ATK 10" card. Now Ciel still has cards but she can choose to end her battle phase. The total damage equals (1001 - 100) + (101 - 10) = 992.In the third test case note that she can destroy the "ATK 0" card by a card with strength equal to 0, but she can't destroy a "DEF 0" card with that card.

#!/usr/bin/env ruby
$damage = 0
def all_destroy?(jjcard, ccard)
  ori_size = ccard.size
  jjcard.each do |jc|
    for i in 0...ccard.size
      if jc[0] == 'ATK' && ccard[i] >= jc[1]
        $damage += ccard[i] - jc[1]
        ccard.delete_at(i)
        break
      elsif jc[0] == 'DEF' && ccard[i] > jc[1]
        ccard.delete_at(i)
        break
      end
    end
  end
  return ori_size - ccard.size == jjcard.size ? ccard : nil
end
n, m = gets.chomp!.split(' ').map(&:to_i)
jcard, ccard = [], []
n.times do
  p, s = gets.chomp!.split(' ')
  jcard << [p, s.to_i]
end
jcard = jcard.sort_by {|v| v[0]}.reverse!
m.times do
  ccard << gets.chomp!.to_i
end
ccard.sort!
tc = ccard.dup
ret = 0
if ccard = all_destroy?(jcard, ccard)
  ccard.each do |cc|
    $damage += cc
  end
end
ret = $damage
$damage = 0
ccard = tc
jcard.sort_by! {|v| v[1]}
jcard.each do |jc|
  next if jc[0] == 'DEF'
  if ccard != nil && ccard.size > 0 && ccard[-1] >= jc[1]
    $damage += ccard[-1] -jc[1];
    ccard.pop
  else
    break
  end
end
puts [ret, $damage].max


Little Petya often travels to his grandmother in the countryside. The grandmother has a large garden, which can be represented as a rectangle 1 × n in size, when viewed from above. This rectangle is divided into n equal square sections. The garden is very unusual as each of the square sections possesses its own fixed height and due to the newest irrigation system we can create artificial rain above each section.Creating artificial rain is an expensive operation. That's why we limit ourselves to creating the artificial rain only above one section. At that, the water from each watered section will flow into its neighbouring sections if their height does not exceed the height of the section. That is, for example, the garden can be represented by a 1 × 5 rectangle, where the section heights are equal to 4, 2, 3, 3, 2. Then if we create an artificial rain over any of the sections with the height of 3, the water will flow over all the sections, except the ones with the height of 4. See the illustration of this example at the picture:  As Petya is keen on programming, he decided to find such a section that if we create artificial rain above it, the number of watered sections will be maximal. Help him.

The first line contains a positive integer n (1 ≤ n ≤ 1000). The second line contains n positive integers which are the height of the sections. All the numbers are no less than 1 and not more than 1000.

Print a single number, the maximal number of watered sections if we create artificial rain above exactly one section.

n=gets.to_i
a=[nil,]
m=1
a+=gets.split.map{|v| v.to_i}

for i in 1..n do
  c=1
  (i+1..n).each do |j|
	if a[j]<=a[j-1] then c+=1
	else break
	end
  end

  (1..i-1).reverse_each do |j|
    if a[j]<=a[j+1] then c+=1
	else break
	end
  end

  if c>m then num=i; m=c; end
end

puts m

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
dp_left = [0]
arr.each_cons(2) do |a,b|
	dp_left << 0
	if b >= a
		dp_left[-1] += dp_left[-2] + 1
	end
end

dp_right = [0]

((n-2).downto(0)).each do |i|
	dp_right << 0
	if arr[i] >= arr[i+1]
		dp_right[-1] += dp_right[-2] + 1
	end
end
dp_right.reverse!
ans_list = dp_left.zip(dp_right).map { |x, y| x + y + 1 }
puts "#{ans_list.max}"

n=gets.chomp.to_i
a=gets.chomp.split(/ /).map{|x|x.to_i}
def toleft(a,k)
    x=a[k]
    i=0
    while a[k-i-1]<=x
        x=a[k-1-i]
        i+=1
    end
    i
end
def toright(a,k)
    x=a[k]
    i=0
    while a[k+i+1]<=x
        x=a[k+1+i]
        i+=1
    end
    i
end
a=a.unshift(a.max+1).push(a.max+1)
p (1..n).map{|x|1+toleft(a,x)+toright(a,x)}.max

gets
areas = gets.chomp.split.map(&:to_i)

max = 0
areas.each_with_index do |a, i|
  cnt = 1

  (i - 1).downto(0).each do |l|
    break if l < 0
    if areas[l] <= areas[l + 1]
      cnt += 1
    else
      break
    end
  end

  (i.succ..areas.size - 1).each do |r|
    if areas[r] <= areas[r - 1]
      cnt += 1
    else
      break
    end
  end

  max = [max, cnt].max
end

puts max

#Infinity
#geti,getia
#Object # dcopy
#
#String # to_a
#   "abc".to_a #=> ["a","b","c"]
#String # to_ia
#   "1 2 3".to_ia #=> [1,2,3]
#
#Array # rsort,rsort!
#   [1,3,2,4].rsort #=> [4,3,2,1]
#
#Integer # divisor
#   24.divisor #=> [1,2,3,4,6,8,12,24]
#
include Math
require "prime"
require "bigdecimal"
require "bigdecimal/math"
require "matrix"
require "pp"
require "benchmark"

Infinity = 1/0.0
class Matrix;def inspect;empty? ? "Matrix.empty(#{row_size}, #{column_size})":"Matrix[\n#{@rows.map(&:inspect).join("\n")}\n]";end;end
def pbin(obj);case obj;when Integer;puts obj.to_s(2);end;end
class String;def to_a;split("");end;end
class String;def to_ia;split.map(&:to_i);end;end
def getia;gets.to_ia;end
def geti;gets.to_i;end
class Object;def dcopy;Marshal.load(Marshal.dump(self));end;end
class Array;def rsort;sort.reverse;end;def rsort!;sort!.reverse!;end;end

n=geti
ls=getia
ans=0
for i in 0...n
    a=0
    for j in 1..i
        break if ls[i-j] > ls[i-j+1]
        a+=1
    end
    for j in 1...(n-i)
        break if ls[i+j] > ls[i+j-1]
        a+=1
    end
    ans=[a,ans].max
end
p ans+1

#!/usr/bin/ruby

n = gets.to_i
arr = gets.split.map(&:to_i)
ans = 0
arr.each_with_index { |v, i|
	left = right = i
	left -= 1 while left > 0 && arr[left-1] <= arr[left]
	right += 1 while right < n-1 && arr[right+1] <= arr[right]
	num = right-left+1
	ans = num if num > ans
}
puts ans

n = gets.to_i
height = [8000] + gets.split.map(&:to_i) + [8000]
left = Array.new(n+2, 0)
right = Array.new(n+2, 0)
for i in 1..n
  if height[i-1] <= height[i]
    left[i] = left[i-1]+1
  end
  if height[n-i+2] <= height[n-i+1]
    right[n-i+1] = right[n-i+2]+1
  end
end
flow = Array.new(n+2) {|i| left[i]+right[i]+1}
print flow.max

n=gets.to_i
a=gets.chomp.split.map(&:to_i)
l,r,i,ans=Array.new(n,0),Array.new(n,0),1,0
while i<n
	l[i] = (a[i] >= a[i-1] ? l[i-1] + 1 : 0);
	i+=1
end
i=n-2
while i>=0
	r[i] = (a[i] >= a[i+1] ? r[i+1]+1 : 0)
	i-=1
end
n.times {|i| ans=l[i]+r[i]+1 if l[i]+r[i]+1>ans}
puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
max = 0
(0...n).each do |i|
  left, right = i, i
  while left>0 and a[left-1] <= a[left]
    left-=1
  end
  while right<n-1 and a[right+1] <= a[right]
    right+=1
  end
  max = right-left+1 if right-left+1 > max
end
puts max

n,*a=gets(p).split.map(&:to_i)<<$$
p (0...n).map{ |x|
    y = x
    1until a[y] < a[y -= 1]
    1until a[x] < a[x += 1]
    x+~y
}.max

N = gets.to_i
map = gets.chomp.split.map{|e| e.to_i}
map.unshift 9999
map.push 9999

ret = 0
1.upto(N) {|center|
  count = 1
  pos = center
  cur_height = map[pos]
  while (cur_height >= map[pos - 1])
    count += 1
    pos -= 1
    cur_height = map[pos]
  end
  pos = center
  cur_height = map[pos]
  while (cur_height >= map[pos + 1])
    count += 1
    pos += 1
    cur_height = map[pos]
  end

  ret = count if ret < count
}
puts ret

n=gets.chomp.to_i
a=gets.chomp.split(/ /).map{|x|x.to_i}
def toleft(a,k)
    x=a[k]
    i=0
    while a[k-i-1]<x
        x=a[k-1-i]
        i+=1
    end
    i
end
def toright(a,k)
    x=a[k]
    i=0
    while a[k+i+1]<x
        x=a[k+1+i]
        i+=1
    end
    i
end
a=a.unshift(a.max+1).push(a.max+1)
p (1..n).map{|x|1+toleft(a,x)+toright(a,x)}.max

gets
areas = gets.chomp.split.map(&:to_i)

max = 0
areas.each_with_index do |a, i|
  #puts "i: #{i}"
  cnt = 1
  l = i - 1
  r = i + 1

  old_vl, old_vr = a, a

  while true do
    old_cnt = cnt
    vl, vr = areas[l], areas[r]

    cnt += 1 if l >= 0 && vl && vl <= old_vl
    cnt += 1 if vr && vr <= old_vr

    #p [l, r, cnt, max]

    l -= 1
    r += 1

    old_vl, old_vr = (l < 0 ? 10000 : vl), vr
    break if old_cnt == cnt
  end

  max = [max, cnt].max
  #puts
end

puts max


There are $$$n$$$ Christmas trees on an infinite number line. The $$$i$$$-th tree grows at the position $$$x_i$$$. All $$$x_i$$$ are guaranteed to be distinct.Each integer point can be either occupied by the Christmas tree, by the human or not occupied at all. Non-integer points cannot be occupied by anything.There are $$$m$$$ people who want to celebrate Christmas. Let $$$y_1, y_2, \dots, y_m$$$ be the positions of people (note that all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct and all $$$y_j$$$ should be integer). You want to find such an arrangement of people that the value $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ is the minimum possible (in other words, the sum of distances to the nearest Christmas tree for all people should be minimized).In other words, let $$$d_j$$$ be the distance from the $$$j$$$-th human to the nearest Christmas tree ($$$d_j = \min\limits_{i=1}^{n} |y_j - x_i|$$$). Then you need to choose such positions $$$y_1, y_2, \dots, y_m$$$ that $$$\sum\limits_{j=1}^{m} d_j$$$ is the minimum possible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of Christmas trees and the number of people. The second line of the input contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$-10^9 \le x_i \le 10^9$$$), where $$$x_i$$$ is the position of the $$$i$$$-th Christmas tree. It is guaranteed that all $$$x_i$$$ are distinct.

In the first line print one integer $$$res$$$ — the minimum possible value of $$$\sum\limits_{j=1}^{m}\min\limits_{i=1}^{n}|x_i - y_j|$$$ (in other words, the sum of distances to the nearest Christmas tree for all people). In the second line print $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$-2 \cdot 10^9 \le y_j \le 2 \cdot 10^9$$$), where $$$y_j$$$ is the position of the $$$j$$$-th human. All $$$y_j$$$ should be distinct and all values $$$x_1, x_2, \dots, x_n, y_1, y_2, \dots, y_m$$$ should be distinct. If there are multiple answers, print any of them.

n, $m = readline.split.map(&:to_i)
x = readline.split.map(&:to_i)

x.sort!

l = r = x[0]
s = []
for xi in x[1..-1] do
  if xi > r + 1
    s << [l,r]
    l = xi
  end
  r = xi
end
s << [l,r]

$d = 1
$res = 0
$y = []
def man(yi)
  $y << yi
  $m -= 1
  $res += $d
  if $m <= 0
    print($res, "\n", $y.join(' '), "\n")
    exit
  end
end
while $m > 0 do
  l,r = s[0]
  s1 = []
  man(l-1)
  man(r+1)
  for l1,r1 in s[1..-1] do
    if l1 > r + 2
      if l1 > r + 3
        s1 << [l-1,r+1]
        l = l1
      end
      man(l1-1)
    end
    r = r1
    man(r+1)
  end
  s1 << [l-1,r+1]
  s = s1
  $d += 1
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n,m = inp
x = inp
buft = []
h = {}
n.times do |i|
  h[x[i]] = true
  buft.push([x[i]-1,1])
  buft.push([x[i]+1,1])
end
ans = []
sum = 0
c = 0
while c < m
  buf,d = buft.shift
  next if(h[buf])
  h[buf] = true
  sum += d
  c += 1
  ans.push(buf)
  buft.push([buf-1,d+1])
  buft.push([buf+1,d+1])
end
puts sum
puts ans.join(" ")

n, $m = readline.split.map(&:to_i)
x = readline.split.map(&:to_i)

x.sort!

l = r = x[0]
s = []
for xi in x[1..-1] do
  if xi > r + 1
    s << [l,r]
    l = xi
  end
  r = xi
end
s << [l,r]

$d = 1
$res = 0
$y = []
def man(yi)
  $y << yi
  $m -= 1
  $res += $d
  if $m <= 0 then
    print($res, "\n", $y.join(' '), "\n")
    exit
  end
end
while $m > 0 do
  l,r = s[0]
  s1 = []
  man(l-1)
  man(r+1)
  for l1,r1 in s[1..-1] do
    if l1 > r + 2
      s1 << [l-1,r+1]
      l = l1
      man(l-1)
    end
    r = r1
    man(r+1)
  end
  s1 << [l-1,r+1]
  s = s1
  $d += 1
end

n, $m = readline.split.map(&:to_i)
x = readline.split.map(&:to_i)

x.sort!

l = r = x[0]
s = []
for xi in x[1..-1] do
  if xi > r + 1
    s << [l,r]
    l = xi
  end
  r = xi
end
s << [l,r]

$d = 1
$res = 0
$y = []
def man(yi)
  $y << yi
  $m -= 1
  $res += $d
  if $m <= 0 then
    print($res, "\n", $y.join(' '), "\n")
    exit
  end
end
while $m > 0 do
  l,r = s[0]
  s1 = []
  man(l-1)
  for l1,r1 in s[1..-1] do
    man(r+1)
    if l1 > r + 2
      s1 << [l-1,r+1]
      l = l1
      man(l-1)
    end
    r = r1
  end
  man(r+1)
  s1 << [l-1,r+1]
  s = s1
  $d += 1
end


Luckily, Serval got onto the right bus, and he came to the kindergarten on time. After coming to kindergarten, he found the toy bricks very funny.He has a special interest to create difficult problems for others to solve. This time, with many $$$1 \times 1 \times 1$$$ toy bricks, he builds up a 3-dimensional object. We can describe this object with a $$$n \times m$$$ matrix, such that in each cell $$$(i,j)$$$, there are $$$h_{i,j}$$$ bricks standing on the top of each other.However, Serval doesn't give you any $$$h_{i,j}$$$, and just give you the front view, left view, and the top view of this object, and he is now asking you to restore the object. Note that in the front view, there are $$$m$$$ columns, and in the $$$i$$$-th of them, the height is the maximum of $$$h_{1,i},h_{2,i},\dots,h_{n,i}$$$. It is similar for the left view, where there are $$$n$$$ columns. And in the top view, there is an $$$n \times m$$$ matrix $$$t_{i,j}$$$, where $$$t_{i,j}$$$ is $$$0$$$ or $$$1$$$. If $$$t_{i,j}$$$ equals $$$1$$$, that means $$$h_{i,j}>0$$$, otherwise, $$$h_{i,j}=0$$$.However, Serval is very lonely because others are bored about his unsolvable problems before, and refused to solve this one, although this time he promises there will be at least one object satisfying all the views. As his best friend, can you have a try?

The first line contains three positive space-separated integers $$$n, m, h$$$ ($$$1\leq n, m, h \leq 100$$$) — the length, width and height. The second line contains $$$m$$$ non-negative space-separated integers $$$a_1,a_2,\dots,a_m$$$, where $$$a_i$$$ is the height in the $$$i$$$-th column from left to right of the front view ($$$0\leq a_i \leq h$$$). The third line contains $$$n$$$ non-negative space-separated integers $$$b_1,b_2,\dots,b_n$$$ ($$$0\leq b_j \leq h$$$), where $$$b_j$$$ is the height in the $$$j$$$-th column from left to right of the left view. Each of the following $$$n$$$ lines contains $$$m$$$ numbers, each is $$$0$$$ or $$$1$$$, representing the top view, where $$$j$$$-th number of $$$i$$$-th row is $$$1$$$ if $$$h_{i, j}>0$$$, and $$$0$$$ otherwise. It is guaranteed that there is at least one structure satisfying the input.

Output $$$n$$$ lines, each of them contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th line should be equal to the height in the corresponding position of the top view. If there are several objects satisfying the views, output any one of them.

Note  The graph above illustrates the object in the first example.    The first graph illustrates the object in the example output for the second example, and the second graph shows the three-view drawing of it.

N,M,H = gets.split.map(&:to_i)
f = gets.split.map(&:to_i)
l = gets.split.map(&:to_i)
t = []
N.times do
  t << gets.split.map(&:to_i)
end

N.times do |i|
  l[i] = [l[i],i]
end
#p l
l.sort_by!{|a| a[0]}.reverse!

ans = Array.new(N){Array.new(M,nil)}

d = []
l.each do |h,i|
  tmp = 0
  M.times do |j|
    if f[j] >= h && t[i][j] != 0
      tmp = j
      break
    end
  end
  ans[i][tmp] = h
end

M.times do |j|
  l.each do |h,i|
    if t[i][j] != 0
      ans[i][j] = f[j]
      break
    end
  end
end
N.times do |i|
  M.times do |j|
    if ans[i][j].nil?
      ans[i][j] = t[i][j] == 0 ? 0 : 1
    end
  end
end

ans.each do |a|
  puts a.join(" ")
end

N, M, H = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
B = gets.split.map(&:to_i)
grid = N.times.map { gets.split.map(&:to_i) }

B.each_with_index do |b, i|
  temp = grid.map(&:dup)

  temp[i].each_with_index do |h, j|
    if h >= 1 && b <= A[j]
      grid[i][j] = b
    end
  end
end

A.each_with_index do |a, i|
  temp = grid.map(&:dup)

  N.times do |j|
    h = temp[j][i]

    if h >= 1 && a <= B[j] && h <= a
      grid[j][i] = a
    end
  end
end

puts grid.map { |l| l.join(' ') }

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

front = gets.chomp.split(" ").map(&:to_i)
left = gets.chomp.split(" ").map(&:to_i)

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

ret = Array.new(n){Array.new(m, -1)}

m.times do |i|
  n.times do |j|
    ret[j][i] = front[i]
  end
end

n.times do |j|
  m.times do |i|
    ret[j][i] = [ret[j][i], left[j]].min
  end
end

m.times do |i|
  n.times do |j|
    if top[j][i] == 0
      ret[j][i] = 0
    end
  end
end

ret.each{|line| puts line.join(" ")}

N,M,H = gets.split.map(&:to_i)
f = gets.split.map(&:to_i)
l = gets.split.map(&:to_i)
t = []
N.times do
  t << gets.split.map(&:to_i)
end

N.times do |i|
  l[i] = [l[i],i]
end
#p l
l.sort_by!{|a| a[0]}.reverse!

ans = Array.new(N){Array.new(M,nil)}

d = []
l.each do |h,i|
  tmp = nil
  N.times do |j|
    tmp = j if f[j] == h && t[i][j] != 0
  end
  if !tmp.nil?
    ans[i][tmp] = h
    d << tmp
  else
    d.each do |j|
      if t[i][j] != 0
        ans[i][j] = h
        break
      end
    end
  end
end
M.times do |i|
  if !d.include?(i)
    l.each do |h,j|
      if t[j][i] != 0
        ans[j][i] = f[i]
        break
      end
    end
  end
end
N.times do |i|
  M.times do |j|
    if ans[i][j].nil?
      ans[i][j] = t[i][j] == 0 ? 0 : 1
    end
  end
end

ans.each do |a|
  puts a.join(" ")
end


The Queen of England has n trees growing in a row in her garden. At that, the i-th (1 ≤ i ≤ n) tree from the left has height ai meters. Today the Queen decided to update the scenery of her garden. She wants the trees' heights to meet the condition: for all i (1 ≤ i < n), ai + 1 - ai = k, where k is the number the Queen chose.Unfortunately, the royal gardener is not a machine and he cannot fulfill the desire of the Queen instantly! In one minute, the gardener can either decrease the height of a tree to any positive integer height or increase the height of a tree to any positive integer height. How should the royal gardener act to fulfill a whim of Her Majesty in the minimum number of minutes?

The first line contains two space-separated integers: n, k (1 ≤ n, k ≤ 1000). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the heights of the trees in the row.

In the first line print a single integer p — the minimum number of minutes the gardener needs. In the next p lines print the description of his actions.  If the gardener needs to increase the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, then print in the corresponding line "+ j x". If the gardener needs to decrease the height of the j-th (1 ≤ j ≤ n) tree from the left by x (x ≥ 1) meters, print on the corresponding line "- j x". If there are multiple ways to make a row of trees beautiful in the minimum number of actions, you are allowed to print any of them.

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

a = gets.split.map{|e| e.to_i}.to_a

mn = 10**9

(1..1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur < mn)
        mn = cur
    end
end

puts mn

(1..1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur == mn)
        (0...a.size).each do |j|
            if (a[j] - (i + k * j) < 0)
                print '+ '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            elsif (a[j] - (i + k * j) > 0)
                print '- '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            end
        end
        break
    end
end

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
mn, c = 0x3f3f3f3f3f3f3f3f, 0
n.times do |i|
	cc, tot = a[i]-i*k, 0
	next if cc <= 0
	n.times{|j| cc,tot=cc+k,tot+(a[j]==cc ? 0 : 1)}
	mn, c = tot, a[i]-i*k if tot < mn
end
p mn
n.times do |i|
	puts "- #{i+1} #{a[i]-c}" if c < a[i]
	puts "+ #{i+1} #{c-a[i]}" if c > a[i]
	c += k
end

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

a = gets.split.map{|e| e.to_i}.to_a

mn = 10**9

(1...1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur < mn)
        mn = cur
    end
end

puts mn

(1...1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur == mn)
        (0...a.size).each do |j|
            if (a[j] - (i + k * j) < 0)
                print '+ '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            elsif (a[j] - (i + k * j) > 0)
                print '- '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            end
        end
        break
    end
end

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

a = gets.split.map{|e| e.to_i}.to_a

mn = 10**9

(0...1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur < mn)
        mn = cur
    end
end

puts mn

(0...1000).each do |i|
    cur = 0
    (0...a.size).each do |j|
        if ((a[j] - (i + k * j)) != 0)
            cur += 1
        end
    end
    if (cur == mn)
        (0...a.size).each do |j|
            if (a[j] - (i + k * j) < 0)
                print '+ '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            elsif (a[j] - (i + k * j) > 0)
                print '- '
                puts (j + 1).to_s + ' ' + (a[j] - (i + k * j)).abs.to_s
            end
        end
        break
    end
end

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
mn, c = 0x3f3f3f3f3f3f3f3f, 0
(-k..k).each do |i|
	cc, tot = a[0] + i, 0
	n.times{|j| cc,tot=cc+k,tot+(a[j]==cc ? 0 : 1)}
	mn, c = tot, a[0] + i if tot < mn
end
p mn
n.times do |i|
	if (c < a[i])
		puts "- #{i+1} #{a[i]-c}"
	elsif (c > a[i])
		puts "+ #{i+1} #{c-a[i]}"
	end
	c += k
end

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
mn, c = 0x3f3f3f3f3f3f3f3f, 0
(-k..k).each do |i|
	cc, tot = a[0] + i, 0
	next if cc <= 0
	n.times{|j| cc,tot=cc+k,tot+(a[j]==cc ? 0 : 1)}
	mn, c = tot, a[0] + i if tot < mn
end
p mn
n.times do |i|
	puts "- #{i+1} #{a[i]-c}" if c < a[i]
	puts "+ #{i+1} #{c-a[i]}" if c > a[i]
	c += k
end