class BinHeap def initialize(buf=nil) @buf=buf||[nil] @max=@buf.size end def add(n) # print :add_s,n a=@buf[i=@max]=n @max+=1 while i>1 && a@buf[c+1] if a>b=@buf[c] @buf[i]=b i=c else break end end @buf[i]=a # print :get_e,ret ret end def dup BinHeap.new(@buf[0..@max-1]) end def buf @buf end def print(*arg) p arg*" " i=s=1 while i<@max p @buf[i,s] i+=s s*=2 end end end n=gets.to_i mod=2000 pq_base=BinHeap.new gets.split.each{|i|pq_base.add i.to_i*mod} b=gets.split.map{|i|i.to_i/2*mod} p (1..n).map{|i| pq=pq_base.dup b.rotate(i).each{|e| pq.add pq.get+e+1 } pq.buf[1..-1].map{|x|x%mod}.max }.min