class BinHeap def initialize(buf=nil) @buf=buf||[nil] @max=@buf.size end def add(n) a=@buf[i=@max]=n @max+=1 while i>1 && a(@buf[c+1]||1e9) break if a<=b=@buf[c] @buf[i]=b i=c end @buf[i]=a ret end def dup BinHeap.new(@buf[0..@max-1]) end end n=gets.to_i pq_base=BinHeap.new gets.split.each{|i|pq_base.add(i.to_i<<11)} b=gets.split.map{|i|i.to_i/2<<11} min=1e9 n.times{ pq=pq_base.dup max=0 b.rotate!.each{|e| pq.add(top=pq.get+e+1) top&=0x7FF max=top if maxmax } p min