N, M = gets.split.map(&:to_i) A = gets.split.map(&:to_i) W = Array.new(N) { [] } Q = [] max_w = 0 M.times do x, w = gets.split.map(&:to_i) x -= 1 max_w = w if max_w < w Q << [x, w] W[x] << w end def f(c) cnt = 0 weight = 0 sum = Array.new(N, 0) counter = Array.new(N + 1, 0) remain = Array.new(N + 1, 0) 0.upto(N - 1) do |i| cnt -= counter[i] weight -= remain[i] weight -= c * cnt sum[i] += weight W[i].each do |w| dist = (c == 0) ? N : w / c next if dist == 0 weight += w n_idx = (i + 1) + dist n_idx = N if n_idx > N counter[n_idx] += 1 remain[n_idx] += w % c if c > 0 cnt += 1 end end cnt = 0 weight = 0 counter = Array.new(N + 1, 0) remain = Array.new(N + 1, 0) (N - 1).downto(0) do |i| cnt -= counter[i] weight -= remain[i] weight -= c * cnt sum[i] += weight W[i].each do |w| dist = (c == 0) ? -1 : w / c next if dist == 0 n_idx = (i - 1) - dist weight += w cnt += 1 if n_idx >= 0 counter[n_idx] += 1 remain[n_idx] += w % c if c > 0 end end end Q.each do |x, w| sum[x] += w end (0..N - 1).all? { |i| sum[i] < A[i] } end if f(0) puts 0 exit elsif !f(max_w) puts -1 exit else ok = max_w ng = 0 while (ok - ng).abs >= 2 c = (ok + ng) / 2 if f(c) ok = c else ng = c end end puts ok end