def up!(y,x,l); puts "#{y - l + 1} #{x} #{y} #{x}"; end N, K = gets.split.map(&:to_i) L = gets.split.map(&:to_i) A = Array.new(K) B = Array.new(N + 1){ [] } MAP = N.times.map{ gets.chomp.chars.map(&:to_i) } Up = Array.new(N + 1){ Array.new(N + 1, 0) } (1 .. N).each do |x| s_ = (1 .. N).inject(0) do |s, y| b = MAP[y - 1][x - 1] next s + 1 if b > 0 B[s] << [y - 1, x] if s > 0 next 0 end B[s_] << [N, x] if s_ > 0 end (1 .. N).each do |l| B[l].sort_by!{|y,x| -y } end L.each do |l| if B[l].empty? j = B.rindex{|q| !q.empty? } y, x = B[j].shift if j > l up!(y,x,l) B[j - l] << [y - l, x] elsif y > l up!(y, x, l) B[l - j] << [y - j, x] else up!(l, x, l) end else y,x = B[l].shift up!(y,x,l) end end