#include #include #include #include template using MinHeap = std::priority_queue, std::greater>; using lint = long long; constexpr lint INF = 1LL << 30; void solve() { int n, m; std::cin >> n >> m; std::vector ots(n); for (auto& t : ots) std::cin >> t; std::vector> ps(m); for (auto& p : ps) { std::cin >> p.first >> p.second; --p.first; } std::sort(ps.begin(), ps.end()); lint ok = INF, ng = -1; while (ok - ng > 1) { lint c = (ok + ng) / 2; auto ts = ots; MinHeap que; lint sum = 0; int j = 0; for (int i = 0; i < n; ++i) { while (j < m && ps[j].first <= i) { lint w = ps[j].second + c * ps[j].first; sum += w; que.push(w); ++j; } while (!que.empty() && que.top() - c * i <= 0) { sum -= que.top(); que.pop(); } ts[i] -= sum - c * i * que.size(); } while (!que.empty()) que.pop(); sum = 0; j = m - 1; for (int i = n - 1; i >= 0; --i) { while (j >= 0 && ps[j].first > i) { lint w = ps[j].second - c * ps[j].first; sum += w; que.push(w); --j; } while (!que.empty() && que.top() + c * i < 0) { sum -= que.top(); que.pop(); } ts[i] -= sum + c * i * que.size(); } if (std::any_of(ts.begin(), ts.end(), [](auto x) { return x < 0; })) { ng = c; } else { ok = c; } } std::cout << (ok == INF ? -1 : ok) << std::endl; } int main() { std::cin.tie(nullptr); std::cout.tie(nullptr); std::ios::sync_with_stdio(false); solve(); return 0; }