Problem:
対空シールド
時は3xxx年，太陽系外の惑星に進出した人類は，大量の隕石の飛来による基地の被害で頭を悩ませていた．国際宇宙防護会社（International Cosmic Protection Company）は，この問題を解決するために新たな対空シールドを開発した．
防護対象の基地は同じサイズの
N
個のユニットが一直線上に等間隔で並んだ形をしており， 1 から
N
までの番号が順に付けられている．ICPCは，これらのユニットに，合計で
M
個のシールドを設置することにした．
i
番目のシールドが能力
a
i
を持ち，ユニット
x
i
に設置されているとする．このとき，あるユニット
u
における強度は，以下の式で表される．
Σ
i=1
M
max(a
i
-(u-x
i
)
2
,0)
シールドはユニットにのみ設置することができ，複数のシールドを同じユニットに設置することもできる．そして，ICPCに支払われる報酬は
N
個のユニットの強度の最小値に比例した額となる．
シールドの能力は全て既に決まっており，位置も最後の 1 つ以外は決定している．最後の 1 つのシールドの位置を決めるにあたって，報酬がなるべく大きくなるようにしたい．このように最後のシールドの位置を決めたときの強度の最小値を求めよ．
Input
入力は最大で 30 個のデータセットからなる．各データセットは次の形式で表される．
N
M
a
1
x
1
…
a
M-1
x
M-1
a
M
N
はユニットの個数，
M
はシールドの個数を表す．
N
と
M
は整数であり，
1 ≤ N ≤ 10
6
，
1 ≤ M ≤ 10
5
を満たす．続く
M
行には各シールドの情報が与えられる．
a
i
と
x
i
はそれぞれシールドの能力と位置を表す整数であり，
1 ≤ a
i
≤ 10
9
，
1 ≤ x
i
≤ N
を満たす．
M
番目のシールドの位置はまだ決定していないため，入力で与えられないことに注意せよ．
入力の終わりは 2 つのゼロからなる行で表される．
Output
各データセットについて，
M
番目のシールドの設置位置を適切に決めたときの，強度の最小値を 1 行に出力せよ．
Sample Input
3 3
2 1
2 2
10
10 4
1 1
1 5
1 9
1
5 7
1000000000 1
1000000000 1
1000000000 3
1000000000 3
1000000000 5
1000000000 5
1
10000 11
10934235 560
3155907 1508
10901182 2457
3471816 3590
10087848 4417
16876957 5583
23145027 6540
15162205 7454
1749653 8481
6216466 9554
7198514
701 14
8181 636
4942 273
1706 282
6758 20
7139 148
6055 629
8765 369
5487 95
6111 77
2302 419
9974 699
108 444
1136 495
2443
0 0
Output for the Sample Input
10
0
5999999960
23574372
985

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
#include <stdlib.h>
using namespace std;
#define rep(i, a, n) for(ll i = a; i < n; i++)
#define ll long long
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

int main() {
    while(true){
        ll n, m; cin >> n >> m;
        if(n*m == 0) break;
        vector<ll> d2(n+2), d1(n+2), d0(n+2);
        rep(i,0,m-1){
            ll a, x; cin >> a >> x;
            ll dx = floor(sqrtl(a));
            ll l = max(1LL,x-dx);
            ll r = min(n,x+dx)+1;
            d2[l] -= 1, d2[r] += 1;
            d1[l] += x*2, d1[r] -= x*2;
            d0[l] += a-x*x, d0[r] -= a-x*x;
        }
        vector<ll> p(n);
        rep(i,1,n+1){
            d2[i] += d2[i-1];
            d1[i] += d1[i-1];
            d0[i] += d0[i-1];
            p[i-1] = d2[i]*i*i+d1[i]*i+d0[i];
        }
        ll a; cin >> a;
        ll ok = 0, ng = 1LL<<50;
        while(ng-ok > 1){
            ll mid = (ok+ng)/2;
            ll l = 0, r = n-1;
            rep(i,0,n){
                if(a+p[i] < mid){
                    l = r+1;
                    break;
                }
                if(p[i] >= mid) continue;
                ll d = floor(sqrtl(p[i]+a-mid));
                chmax(l,i-d);
                chmin(r,i+d);
            }
            if(l <= r) ok = mid;
            else ng = mid;
        }
        cout << ok << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 34456
final_rank: 6

code_snippet: #include <bits/stdc++.h>
#include <unordered_map>
#include <stdlib.h>
using namespace std;
#define rep(i, a, n) for(ll i = a; i < n; i++)
#define rrep(i, a, n) for(ll i = a; i >= n; i--)
#define ll long long
#define pii pair<int, int>
#define pll pair<ll, ll>
#define all(x) (x).begin(), (x).end()
//constexpr ll MOD = 1000000007;
constexpr ll MOD = 998244353;
constexpr int IINF = 1001001001;
constexpr ll INF = 1LL<<60;
template<class t,class u> void chmax(t&a,u b){if(a<b)a=b;}
template<class t,class u> void chmin(t&a,u b){if(b<a)a=b;}

int main() {
    while(true){
        ll n, m; cin >> n >> m;
        if(n*m == 0) break;
        vector<ll> d2(n+2), d1(n+2), d0(n+2);
        rep(i,0,m-1){
            ll a, x; cin >> a >> x;
            ll dx = floor(sqrtl(a));
            ll l = max(1LL,x-dx);
            ll r = min(n,x+dx)+1;
            d2[l] -= 1, d2[r] += 1;
            d1[l] += x*2, d1[r] -= x*2;
            d0[l] += a-x*x, d0[r] -= a-x*x;
        }
        vector<ll> p(n);
        rep(i,1,n+1){
            d2[i] += d2[i-1];
            d1[i] += d1[i-1];
            d0[i] += d0[i-1];
            p[i-1] = d2[i]*i*i+d1[i]*i+d0[i];
        }
        ll a; cin >> a;
        ll ok = 0, ng = 1LL<<50;
        while(ng-ok > 1){
            ll mid = (ok+ng)/2;
            ll l = 0, r = n-1;
            rep(i,0,n){
                if(a+p[i] < mid){
                    l = INF;
                    break;
                }
                if(p[i] >= mid) continue;
                ll d = floor(sqrtl(p[i]+a-mid));
                // while(d*d > p[i]+a-mid) d--;
                // while((d+1)*(d+1) <= p[i]+a-mid) d++;
                chmax(l,i-d);
                chmin(r,i+d);
            }
            if(l <= r) ok = mid;
            else ng = mid;
        }
        cout << ok << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 190
memory_kb: 34356
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    while(true){
        int N, M;
        cin >> N >> M;
        if(!cin || (N==0 && M==0)) break;

        vector<ll> d2(N+2,0), d1(N+2,0), d0(N+2,0);

        // --- 入力読み込み ---
        vector<pair<ll,int>> shields;
        shields.reserve(M-1);
        for(int i = 1; i < M; i++){
            ll a; int x;
            cin >> a >> x;
            shields.emplace_back(a, x);
        }
        ll A;  // 最後のシールドの能力
        cin >> A;

        // --- M-1 個のシールドの寄与を差分配列に乗せる ---
        // 各シールド (a,x) は [x-d, x+d] の範囲に
        //   f(u) = a - (u - x)^2 = (-1)*u^2 + (2x)*u + (a - x^2)
        // を加算するので、三次元いもす法で差分を取る。
        for(auto [a,x] : shields){
            int d = floor(sqrt((long double)a));
            int l = max(1, x - d);
            int r = min(N, x + d);
            ll c2 = -1;
            ll c1 = 2LL * x;
            ll c0 = a - (ll)x * x;
            d2[l] += c2;    d2[r+1] -= c2;
            d1[l] += c1;    d1[r+1] -= c1;
            d0[l] += c0;    d0[r+1] -= c0;
        }

        // --- 差分を累積和に戻して S[u] を得る ---
        vector<ll> S(N+1);
        ll cur2 = 0, cur1 = 0, cur0 = 0;
        for(int u = 1; u <= N; u++){
            cur2 += d2[u];
            cur1 += d1[u];
            cur0 += d0[u];
            // S[u] = cur2*u^2 + cur1*u + cur0
            S[u] = cur2*(ll)u*u + cur1*(ll)u + cur0;
        }

        // --- 最後のシールドを置いたときの
        //     「最小強度の最大化」問題を二分探索で解く ---
        // 判定関数：目標値 T を実現できる位置 p があるか
        auto feasible = [&](ll T){
            // 位置 p の候補区間 [L,R]
            int L = 1, R = N;
            for(int u = 1; u <= N; u++){
                // 最後のシールドを u に寄与させたとしても S[u] + A  < T なら無理
                if(S[u] + A < T) return false;

                // もし S[u] < T なら、
                //   A - (u-p)^2 ≥ T - S[u]
                //   ⇔ (u-p)^2 ≤ A + S[u] - T
                if(S[u] < T){
                    ll delta = A + S[u] - T;
                    // delta ≥ 0 は保証済み
                    ll d = floor(sqrt((long double)delta));
                    // sqrt 誤差補正
                    while((d+1)*(d+1) <= delta) d++;
                    while(d*d > delta)        d--;
                    int li = u - d;
                    int ri = u + d;
                    if(li > L) L = li;
                    if(ri < R) R = ri;
                    if(L > R) return false;
                }
                // S[u] ≥ T の場合は制約を与えない
            }
            return L <= R;
        };

        // 探索範囲は [0, max S + A]
        ll lo = 0, hi = *max_element(S.begin()+1, S.end()) + A;
        while(lo < hi){
            ll mid = (lo + hi + 1) >> 1;
            if(feasible(mid)) lo = mid;
            else             hi = mid - 1;
        }

        cout << lo << "\n";
    }
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 36116
final_rank: 4

code_snippet: #include "bits/stdc++.h"
using namespace std;

#define REP(i, n) for (int i = 0; i < n; i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define FOR(i, m, n) for (ll i = m; i < n; i++)
#define FORR(i, m, n) for (ll i = m; i >= n; i--)
#define REPO(i, n) for (ll i = 1; i <= n; i++)
#define ll long long
#define INFll (ll)1ll << 60 
#define MINFll (-1 * INFll)
#define ALL(n) n.begin(), n.end()
#define MOD (ll)998244353
#define P pair<ll, ll>

#define PP pair<P, ll>

void solve(ll n, ll m){
    vector<ll> a(m), x(m);
        REP(i, m - 1){
            cin >> a[i] >> x[i];
        }
        vector<PP> v;
        REP(i, m - 1){
            ll b = sqrt(a[i]);
            ll l = max(x[i] - b, 1ll);
            ll r = min(x[i] + b, n) + 1;
            //cout << l <<" " << r << endl;
            PP now = PP(P(l, r), i);
            v.push_back(now);
        }
        sort(ALL(v));
        ll idx = 0, ca = 0, cx2 = 0, cx = 0;
        vector<ll> u(n + 10);
        priority_queue<P, vector<P>, greater<P>> q;
        REPO(i, n){
            while(idx < v.size() and v[idx].first.first == i){
                ll e = v[idx].second;
                ca += a[e];
                cx2 += x[e] * x[e];
                cx += x[e];
                q.push(P(v[idx].first.second, v[idx].second));
                idx++;
            }
            while(!q.empty() and q.top().first <= i){
                ll e = q.top().second;
                ca -= a[e];
                cx2 -= x[e] * x[e];
                cx -= x[e];
                q.pop();
            }
            //cout << i << " " << ca << " " << cx2 << " " << cx << " " << q.size() << endl;
            u[i] = ca - cx2 + 2 * cx * i - i * i * q.size();
        }
        /*
        REPO(i, n){
            cout << u[i] <<" ";
        }
        cout << endl;
        */
        ll aa;
        cin >> aa;

        ll ok = 0;
        ll ng =  (ll)1e16;
        while(abs(ok - ng) > 1){
            ll mid = (ok + ng) >> 1;
            ll l = 1, r = n;
            bool ook = true;
            //cout << mid << endl;
            REPO(i, n){
                ll dx = mid - u[i];
                //cout << aa << " " << u[i] << " " << dx << endl;
                if(dx <= 0) continue;
                if(aa < dx){
                    ook = false;
                    continue;
                }
                l = max(l, i - (ll)sqrt(aa - dx));
                r = min(r, i + (ll)sqrt(aa - dx));
            }
            if(!ook)ng = mid;
            else if(l <= r)ok = mid;
            else ng = mid;
        }
        cout << ok << endl;
}
int main(){
    while(1){
        ll n, m;
        cin >> n >> m;
        if(n == 0 and m == 0)break;
        solve(n, m);
    }   
}
accuracy: 1
time_ms: 200
memory_kb: 18212
final_rank: 2

code_snippet: #define _USE_MATH_DEFINES
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using H = pair<int, int>;
using P = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
#define all(a) (a).begin(), (a).end()
#define fs first
#define sc second
#define rng(i, s, n) for(int i = (s) ; i < (n) ; i++)
#define rep(i, n) rng(i, 0, (n))
#define mkp make_pair
#define vec vector
#define pb emplace_back
#define siz(a) int((a).size())
#define crdcomp(b) sort(all((b))); (b).erase(unique(all((b))), (b).end())
#define getidx(b, i) (lower_bound(all((b)), (i))-(b).begin())
#define cdf(n) for(int __quetimes=(n); __quetimes>0; __quetimes--)
#define readv(a, n) (a).resize((n), 0); rep(i, (n)) (a)[i]=read()
#define found(a, x) (a.find(x)!=a.end())
#define slp(x, y) make_pair(min((x), (y)), max((x), (y)))
constexpr ll mod = (ll)1e9 + 7;
constexpr ll Mod = 998244353;
constexpr ld EPS = 1e-10;
constexpr ll inf = (ll)3 * 1e18;
constexpr int Inf = 1e9 + 10;
constexpr int dx[] = { -1, 1, 0, 0 }, dy[] = { 0, 0, -1, 1 };
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }
template<class T = ll>T read() { T u, k = scanf("%lld", &u); return u; }
template<typename T>bool ina(pair<T, T> t, T h, T w) { return 0 <= t.fs && t.fs < h && 0 <= t.sc && t.sc < w; }
ll gcd(ll i, ll j) { return j ? gcd(j, i % j) : i; }
template<typename T>void fin(T x) { cout << x << endl; exit(0); }
void outv(vector<ll>v) { for (int i = 0;i < v.size();i++) printf("%lld%c", v[i], " \n"[i == int(v.size()) - 1]); }/*
#include<atcoder/all>
using namespace atcoder;//*/
//-------------------------------------------------------------

signed main() {
	int n, m;
	while (cin >> n >> m && n > 0) {
		vl a(m), x(m);
		rep(i, m) {
			cin >> a[i];
			if (i < m - 1) cin >> x[i], x[i]--;
		}

		vl b(n + 10);
		vl c(n + 10), d(n + 10);
		vl e(n + 10), f(n + 10);
		vl g(n + 10), h(n + 10);

		vl sum(n + 10);

		for (int i = 0;i < m - 1;i++) {
			ll l = -1, r = x[i] - 1, mid;
			if (x[i] > 0) {
				while (r - l > 1) {
					mid = (l + r) / 2;
					if ((x[i] - mid) * (x[i] - mid) < a[i]) r = mid;
					else l = mid;
				}

				if (r == x[i] - 1) {
					sum[r] += a[i] - 1;
				}
				else if (r == x[i] - 2) {
					sum[r] += a[i] - 4;
					sum[r + 1] += a[i] - 1;
				}
				else {
					b[r] += a[i];
					b[x[i]] -= a[i];

					if (r > 0) c[r - 1] -= (x[i] - r) * (x[i] - r);

					e[x[i] - 1] += 1;
					if (r > 0) e[r - 1] += -((x[i] - r) * 2 - 1);

					g[x[i] - 2] += 2;
					if (r > 0) g[r - 1] += -2;
				}
			}
			l = x[i], r = n;
			while (r - l > 1) {
				mid = (l + r) / 2;
				if ((x[i] - mid) * (x[i] - mid) < a[i]) l = mid;
				else r = mid;
			}

			if (l == x[i]) {
				sum[l] += a[i];
			}
			else if (l == x[i] + 1) {
				sum[l - 1] += a[i];
				sum[l] += a[i] - 1;
			}
			else {
				b[x[i]] += a[i];
				b[l + 1] -= a[i];

				d[l + 1] -= (x[i] - l) * (x[i] - l);

				f[x[i] + 1] += 1;
				f[l + 1] += -((l - x[i]) * 2 - 1);

				h[x[i] + 2] += 2;
				h[l + 1] += -2;
			}
		}
		for (int i = 1;i < n;i++) {
			h[i] += h[i - 1];
		}
		for (int i = n - 2;i >= 0;i--) {
			g[i] += g[i + 1];
		}

		for (int i = 1;i < n;i++) {
			f[i] += f[i - 1] + h[i];
		}
		for (int i = n - 2;i >= 0;i--) {
			e[i] += e[i + 1] + g[i];
		}

		for (int i = 1;i < n;i++) {
			d[i] += d[i - 1] + f[i];
		}
		for (int i = n - 2;i >= 0;i--) {
			c[i] += c[i + 1] + e[i];
		}

		for (int i = 1;i < n;i++) b[i] += b[i - 1];
		for (int i = 0;i < n;i++) {
			b[i] -= c[i] + d[i];
		}

		for (int i = 0;i < n;i++) sum[i] += b[i];


		ll l = 0, r = 0, mid;
		rep(i, m) r += a[i];
		while (r - l > 1) {
			mid = (l + r) / 2;
			bool flag = false;
			vi cnt(n + 1);
			int fuga = 0;
			for (int i = 0;i < n;i++) if (sum[i] < mid) {
				if (mid - sum[i] > a[m - 1]) {
					flag = true;
					break;
				}
				fuga++;
				ll dist = sqrt(a[m - 1] - (mid - sum[i]));
				cnt[max(0ll, i - dist)]++;
				cnt[min(ll(n), i + dist + 1)]--;
			}
			if (flag) {
				r = mid;
				continue;
			}
			for (int i = 1;i < n;i++) cnt[i] += cnt[i - 1];
			flag = false;
			rep(i, n) if (cnt[i] == fuga) {
				l = mid;
				flag = true;
				break;
			}
			if (!flag) r = mid;
		}
		cout << l << endl;
	}
}
accuracy: 1
time_ms: 450
memory_kb: 70888
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll = long long;

#define rep(i, n) for(ll i = 0; i < (n); ++i)
#define all(A) A.begin(), A.end()

template<class T>
void print(vector<T> a) {
  cout << '[';
  for(auto x : a) cout << x << ' ';
  cout << ']' << endl;
}

void print(auto... vs) {
  ((cout << vs << ' '), ...) << endl;
}

ll sqrtz(ll n) {
  return (ll)floor(sqrtl(n));
}

bool isOK(const vector<ll> &str, ll mid, ll a) {
  ll N = str.size() - 1; // n = N + 1
  vector<ll> diff(N, 0);
  rep(i, N) {
    diff[i] = max(mid - str[i], 0LL);
  }
  // print(mid);
  // print(diff);
  
  vector<ll> imos(N + 1, 0);
  rep(i, N) {
    ll k = diff[i];
    if(a - k < 0) return false;
    ll l = max(i - sqrtz(a - k), 0LL);
    ll r = min(i + sqrtz(a - k), N - 1);
    if(diff[i] == 0) l = 0, r = N-1;
    imos[l] += 1;
    imos[r+1] -= 1;
  }
  rep(i, N+1) {
    if(i == 0) continue;
    imos[i] += imos[i-1];
  }
  ll mx = *max_element(all(imos));
  return mx >= N;
}

int main() {
  while(1) {
    ll N, M; cin >> N >> M;
    if(N + M == 0) break;
    
    vector<array<ll, 2>> pro(M);
    rep(i, M) {
      ll a, x = 0;
      cin >> a;
      if(i < M-1) cin >> x;
      x--;
      pro[i] = {a, x};
    }
    
    vector<array<ll, 3>> v3(N+1, {0, 0, 0});
    rep(i, M-1) {
      auto [a, x] = pro[i];
      ll l = max(x - sqrtz(a), 0LL);
      ll r = min(x + sqrtz(a), N-1);
      v3[l][0] += (-1);
      v3[l][1] += (2 * x);
      v3[l][2] += (a - x * x);
      v3[r+1][0] -= (-1);
      v3[r+1][1] -= (2 * x);
      v3[r+1][2] -= (a - x * x);      
    }
    rep(i, N+1) {
      if(i == 0) continue;
      rep(j, 3) {
        v3[i][j] += v3[i-1][j];
      }
    }
    
    vector<ll> str(N+1, 0);
    rep(i, N+1) {
      auto [a, b, c] = v3[i];
      str[i] = a * i * i + b * i + c;
    }
    // print(str);
    
    ll ok = 0, ng = 1e15;
    while(abs(ok - ng) > 1) {
      ll mid = (ok + ng) / 2;
      if(isOK(str, mid, pro[M-1][0])) ok = mid;
      else ng = mid;
    }
    cout << ok << '\n';
    
  }
  return 0;
}
accuracy: 1
time_ms: 1070
memory_kb: 51764
final_rank: 15

code_snippet: #include <bits/stdc++.h>
#include <atcoder/all>

using namespace std;
using ll = long long;
using pll = pair<ll,ll>;
using bint = __int128_t;
#define rep(i, s, t) for (ll i = s; i < (ll)(t); i++)
#define rrep(i, s, t) for(ll i = (ll)(t) - 1; i >= (ll)(s); i--)
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define TT template<typename T>
TT using vec = vector<T>;
TT using minheap = priority_queue<T, vector<T>, greater<T>>;
TT using maxheap = priority_queue<T>;
template<class T> bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }
template<class T> bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }
struct io_setup {
    io_setup() {
        ios::sync_with_stdio(false);
        std::cin.tie(nullptr);
        cout << fixed << setprecision(15);
    }
} io_setup;

std::ostream &operator<<(std::ostream &dest, __int128_t value) {
  std::ostream::sentry s(dest);
  if (s) {
    __uint128_t tmp = value < 0 ? -value : value;
    char buffer[128];
    char *d = std::end(buffer);
    do {
      --d;
      *d = "0123456789"[tmp % 10];
      tmp /= 10;
    } while (tmp != 0);
    if (value < 0) {
      --d;
      *d = '-';
    }
    int len = std::end(buffer) - d;
    if (dest.rdbuf()->sputn(d, len) != len) {
      dest.setstate(std::ios_base::badbit);
    }
  }
  return dest;
}

__int128 parse(string &s) {
  __int128 ret = 0;
  for (size_t i = 0; i < s.length(); i++)
    if ('0' <= s[i] && s[i] <= '9')
      ret = 10 * ret + s[i] - '0';
  return ret;
}

std::istream &operator>>(std::istream &dest, __int128_t &value) {
    string s;
    dest >> s;
    value = parse(s);
    return dest;
}

TT struct monotone_imos {
    int n;
    vec<vec<T>> dat;
    int R;
    monotone_imos(int n) : n(n), R(0) {
        dat.resize(4);
        for (int i = 0; i < 4; i++) dat[i].assign(n, 0);
    }

    void add(int i, T x) { add(i, i + 1, 0, 0, x); }

    void add(int l, int r, T x) { add(l, r, 0, 0, x); }

    void add(int s, T a, T b, T c) {  // a(x-s)^2 + b(x - s) + cを [s, n) にadd
        assert(R <= s);
        assert(s < n);
        dat[0][s] += c;
        if (s + 1 < n) dat[0][s + 1] += a + b - 2 * c;
        if (s + 2 < n) dat[0][s + 2] += a - b + c;
    }

    void add(int l, int r, T a, T b, T c) {
        assert(l <= r);
        assert(R <= l);
        assert(r <= n);
        add(l, a, b, c);
        int len = r - l;
        if (r < n)
            add(r, -(a), -(2 * a * len + b), -(b * len + c + a * len * len));
    }

    void proceed() {
        assert(R < n);
        dat[1][R] += dat[0][R];
        if (R) {
            dat[1][R] += dat[1][R - 1];
        }

        dat[2][R] = dat[1][R];
        if (R) {
            dat[2][R] += dat[2][R - 1];
        }

        dat[3][R] = dat[2][R];
        if (R) {
            dat[3][R] += dat[3][R - 1];
        }
        R++;
    }

    void all_proceed() {
        while (R < n) {
            proceed();
        }
    }

    T get(int i) const {
        assert(0 <= i && i < R);
        return dat[3][i];
    }

    T operator[](int i) const {
        return get(i);
    }

    friend ostream &operator<<(ostream &os, monotone_imos imos) {
        for (int i = 0; i < imos.n; i++) {
            if (i < imos.R)
                os << imos.dat[3][i];
            else
                os << "yet";
            os << (i != imos.n - 1 ? " " : "");
        }
        return os;
    }
};

int solve(){
  int n,m;
  cin>>n>>m;
  if(n==0) return 0;
  vector<ll> a(m),x(m);
  rep(i,0,m-1) cin>>a[i]>>x[i],x[i]--;
  cin>>a[m-1];
  ll shf=1e5;
  monotone_imos<ll> imos(shf+n+shf);
  rep(i,0,m-1){
    int sq=sqrt(a[i]);
    if(sq*sq>a[i]) sq--;
    ll l=x[i]+shf-sq;
    ll r=x[i]+shf+sq+1;
    imos.add(l,r,-1,-2*l+2*(x[i]+shf),a[i]-(x[i]+shf)*(x[i]+shf)-l*l+2*(x[i]+shf)*l);
  }
  imos.all_proceed();
  vector<ll> now_val(n);
  rep(i,0,n) now_val[i]=imos[shf+i];
  vector<int> p(n);
  iota(p.begin(),p.end(),0);
  sort(p.begin(),p.end(),[&](int i,int j){
    return now_val[i]<now_val[j];
  });
  vector<ll> adv;
  {
    rep(i,0,a.back()){
      ll tmp=a.back()-i*i;
      if(tmp<=0) break;
      adv.push_back(tmp);
    }
    reverse(adv.begin(),adv.end());
  }
  auto get_width=[&](ll x){
    return adv.end()-lower_bound(adv.begin(),adv.end(),x);
  };
  ll up=1e18;
  ll dw=0;
  while(up-dw>1){
    ll md=(up+dw)/2;
    int nl=0,nr=n;
    for(int i:p){
      if(now_val[i]>=md) break;
      int w=get_width(md-now_val[i]);
      if(w==0){
        nr=-1,nl=n;
        break;
      }
      chmax(nl,i-w+1);
      chmin(nr,i+w);
    }
    if(nl<nr) dw=md;
    else up=md;
  }
  cout<<dw<<"\n";
  return 1;
}

int main() {
  //monotone_imos<ll> imos(10);
  //imos.add(l, r, a, c, b)
  //a(x-l)^2 + b(x-l) + c  を [l, r) に足す
  //imos.all_proceed() でデータにアクセスできるようになる
  //データへのアクセスは imos[i]

  //imos.add(0, 5, 1, 1, 1);
  //imos.all_proceed();
  //1 3 7 13 21 0 0 0 0 0
  //cout << imos << endl;

  //imos.add(4, 9, 1, 1, 1);
  //imos.all_proceed();
  //0 0 0 0 1 3 7 13 21 0
  //cout << imos << endl;

  //imos.add(4, 9, 0, 3, 5);
  //imos.all_proceed();
  //0 0 0 0 5 8 11 14 17 0
  //cout << imos << endl;
  while(solve());
}
accuracy: 1
time_ms: 270
memory_kb: 56728
final_rank: 11

code_snippet: //#pragma GCC optimize("O3")
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for (ll i=0;i<(ll)n;i++)
#define rrep(i,n) for (ll i=n-1;i>=(ll)0;i--)
#define loop(i,m,n) for(ll i=m;i<=(ll)n;i++)
#define rloop(i,m,n) for(ll i=m;i>=(ll)n;i--)
#define vl vector<long long>
#define vvl vector<vector<long long>>
#define vdbg(a) rep(ii,a.size()){cout<<a[ii]<<" ";}cout<<endl;
#define vvdbg(a) rep(ii,a.size()){rep(jj,a[ii].size()){cout<<a[ii][jj]<<" ";}cout<<endl;}
#define setdbg(a) for(const auto & ii:a){cout<<ii<<" ";}cout<<endl;
#define inf 4000000000000000000LL
#define mod 998244353LL
#define eps 0.000000001
//#define mod 1000000007LL
random_device rnd;// 非決定的な乱数生成器
mt19937 mt(rnd());// メルセンヌ・ツイスタの32ビット版、引数は初期シード

//#include<boost/multiprecision/cpp_int.hpp>
//#define bbi boost::multiprecision::cpp_int

//#include<atcoder/lazysegtree>

ll introot(ll n) {
	if (n < 0) return false;
	ll sqrtN = static_cast<ll>(sqrt(n));
	ll ans=0;
	loop(i,max(0LL,sqrtN-2),sqrtN+2){
		if(i * i <= n)ans=i;
	}
	return ans;
}

template <typename T>
struct offset_vector {
    vector<T> data;
    const size_t offset;

    /** @brief 負のインデックスをサポートするベクトル
     * @param n 正のインデックスのサイズ
     * @param offset 負のインデックスに拡張する数
     * @param init_val 初期値（デフォルトはT()）
     */
    offset_vector(size_t n, size_t offset = 0, T init_val = T()) : offset(offset) {
        data.resize(n + offset, init_val);
    }

    T& operator[](size_t i) {
        assert(0 <= i + offset);
        assert(i + offset < data.size());
        return data[i + offset];
    }

    auto begin() {
        return data.begin();
    }
    auto end() {
        return data.end();
    }
    auto rbegin() {
        return data.rbegin();
    }
    auto rend() {
        return data.rend();
    }
    auto size() const {
        return data.size();
    }
    size_t positive_size() const {
        return data.size() - offset;
    }
    auto empty() const {
        return data.empty();
    }
    auto front() {
        assert(!data.empty());
        return data.front();
    }
    auto back() {
        assert(!data.empty());
        return data.back();
    }

    void push_back(const T& value) {
        data.push_back(value);
    }
    void pop_back() {
        assert(offset < data.size());
        assert(!data.empty());
        data.pop_back();
    }

    friend ostream& operator<<(ostream& os, const offset_vector<T>& v) {
        for (size_t i = 0; i < v.size(); ++i) {
            if (i != 0) os << " ";
            os << v.data[i];
        }
        os << "\n";
        return os;
    }
};


ll solve(){
	int n,m;
	cin>>n>>m;
	if(n==0&&m==0){return 1;}
	
	vector<offset_vector<ll>> imos(4,offset_vector<ll>(n+32000,32000,0));
	rep(i,m-1){
		ll a,x;
		cin>>a>>x;
		ll rta=introot(a);
		imos[1][x-rta]+=a-rta*rta;
		imos[2][x-rta+1]+=rta*rta-(rta-1)*(rta-1);
		imos[3][x-rta+2]+=-2;
		imos[1][x+rta+1]+=rta*rta-a;
		imos[2][x+rta+1]+=rta*rta-(rta-1)*(rta-1);
		imos[3][x+rta+1]+=2;
	}

	rloop(i,3,1){
		imos[i][0]+=0;
		ll sum=0;
		loop(j,-32000,n){
			sum+=imos[i][j];
			imos[i-1][j]+=sum;
		}
	}

	vl cost(n);
	rep(i,n)cost[i]=imos[0][i+1];
	
	//vdbg(cost);
	ll a;
	cin>>a;
	ll mn=0,mx=1e14;

	while(mn!=mx){
		ll mid=(mn+mx+1)/2;
		//cout<<mid<<endl;
		ll l=0,r=n-1;
		rep(i,n){
			if(cost[i]>=mid)continue;
			if(cost[i]+a<mid){
				l=n;
				r=0;
				break;
			}
			ll husoku=mid-cost[i];
			//lに置いた時左過ぎたらlを加算
			while(l<i&&a-((l-i)*(l-i))<husoku)l++;
			//rも同様に右過ぎたらrを減算。
			while(r>i&&a-((r-i)*(r-i))<husoku)r--;
		}
		if(l>r)mx=mid-1;
		else mn=mid;
	}
	cout<<mn<<endl;
	return 0;
}

//メイン
int main(){
	while(solve()==0);
	return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 50564
final_rank: 9

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define FOR(i,l,r) for(ll i=l;i<r;i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(A) A.begin(),A.end()
#define LB(A,x) (lower_bound(ALL(A),x)-A.begin())
#define UB(A,x) (upper_bound(ALL(A),x)-A.begin())
int main(){
    while(1){
        ll N,M;cin>>N>>M;
        if(!N)return 0;
        vector<ll>F(N+100000);
        REP(i,M-1){
            ll a,x;cin>>a>>x;x--;
            ll t=sqrt(a);
            while((t+1)*(t+1)<=a)t++;
            if(t*t>a)t--;
            F[x-t+50000]+=a-t*t;
            F[x-t+50001]+=2*t-1-2*a+2*t*t;
            F[x-t+50002]+=a-t*t-2*t-1;
            F[x+t+50001]+=2*t+1-a+t*t;
            F[x+t+50002]+=2*a-2*t*t-2*t+1;
            F[x+t+50003]+=t*t-a;
        }
        REP(i,F.size()-1)F[i+1]+=F[i];
        REP(i,F.size()-1)F[i+1]+=F[i];
        REP(i,F.size()-1)F[i+1]+=F[i];
        //REP(i,N)cout<<F[50000+i]<<" ";cout<<endl;
        ll a;cin>>a;
        ll l=0,r=1e18;
        while(r-l>1){
            ll m=(l+r)/2;
            ll x=0,y=N-1;
            REP(i,N)if(F[i+50000]<m){
                if(F[i+50000]+a<m){x=1e10;break;}
                ll c=F[i+50000]+a-m;
                ll t=sqrt(c);
                while((t+1)*(t+1)<=c)t++;
                if(t*t>c)t--;
                if(x<i-t)x=i-t;
                if(y>i+t)y=i+t;
            }
            if(x<=y)l=m;
            else r=m;
        }
        cout<<l<<endl;
    }
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 12860
final_rank: 1

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

#include <unistd.h>

namespace fastio {
static constexpr uint32_t SZ = 1 << 17;
char ibuf[SZ];
char obuf[SZ];
char out[100];
// pointer of ibuf, obuf


uint32_t pil = 0, pir = 0, por = 0;

struct Pre {
    char num[10000][4];
    constexpr Pre() : num() {
        for (int i = 0; i < 10000; i++) {
            int n = i;
            for (int j = 3; j >= 0; j--) {
                num[i][j] = n % 10 | '0';
                n /= 10;
            }
        }
    }
} constexpr pre;

inline void load() {
    memmove(ibuf, ibuf + pil, pir - pil);
    pir = pir - pil + fread(ibuf + pir - pil, 1, SZ - pir + pil, stdin);
    pil = 0;
    if (pir < SZ)
        ibuf[pir++] = '\n';
}

inline void flush() {
    fwrite(obuf, 1, por, stdout);
    por = 0;
}

void rd(char &c) {
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
}

void rd(string &x) {
    x.clear();
    char c;
    do {
        if (pil + 1 > pir)
            load();
        c = ibuf[pil++];
    } while (isspace(c));
    do {
        x += c;
        if (pil == pir)
            load();
        c = ibuf[pil++];
    } while (!isspace(c));
}

template <typename T> void rd_real(T &x) {
    string s;
    rd(s);
    x = stod(s);
}

template <typename T> void rd_integer(T &x) {
    if (pil + 100 > pir)
        load();
    char c;
    do
        c = ibuf[pil++];
    while (c < '-');
    bool minus = 0;
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (c == '-') {
            minus = 1, c = ibuf[pil++];
        }
    }
    x = 0;
    while ('0' <= c) {
        x = x * 10 + (c & 15), c = ibuf[pil++];
    }
    if constexpr (is_signed<T>::value || is_same_v<T, i128>) {
        if (minus)
            x = -x;
    }
}

void rd(int &x) {
    rd_integer(x);
}
void rd(ll &x) {
    rd_integer(x);
}
void rd(i128 &x) {
    rd_integer(x);
}
void rd(uint &x) {
    rd_integer(x);
}
void rd(ull &x) {
    rd_integer(x);
}
void rd(u128 &x) {
    rd_integer(x);
}
void rd(double &x) {
    rd_real(x);
}
void rd(long double &x) {
    rd_real(x);
}

template <class T, class U> void rd(pair<T, U> &p) {
    return rd(p.first), rd(p.second);
}
template <size_t N = 0, typename T> void rd_tuple(T &t) {
    if constexpr (N < std::tuple_size<T>::value) {
        auto &x = std::get<N>(t);
        rd(x);
        rd_tuple<N + 1>(t);
    }
}
template <class... T> void rd(tuple<T...> &tpl) {
    rd_tuple(tpl);
}

template <size_t N = 0, typename T> void rd(array<T, N> &x) {
    for (auto &d : x)
        rd(d);
}
template <class T> void rd(vector<T> &x) {
    for (auto &d : x)
        rd(d);
}

void read() {}
template <class H, class... T> void read(H &h, T &...t) {
    rd(h), read(t...);
}

void wt(const char c) {
    if (por == SZ)
        flush();
    obuf[por++] = c;
}
void wt(const string s) {
    for (char c : s)
        wt(c);
}
void wt(const char *s) {
    size_t len = strlen(s);
    for (size_t i = 0; i < len; i++)
        wt(s[i]);
}

template <typename T> void wt_integer(T x) {
    if (por > SZ - 100)
        flush();
    if (x < 0) {
        obuf[por++] = '-', x = -x;
    }
    int outi;
    for (outi = 96; x >= 10000; outi -= 4) {
        memcpy(out + outi, pre.num[x % 10000], 4);
        x /= 10000;
    }
    if (x >= 1000) {
        memcpy(obuf + por, pre.num[x], 4);
        por += 4;
    } else if (x >= 100) {
        memcpy(obuf + por, pre.num[x] + 1, 3);
        por += 3;
    } else if (x >= 10) {
        int q = (x * 103) >> 10;
        obuf[por] = q | '0';
        obuf[por + 1] = (x - q * 10) | '0';
        por += 2;
    } else
        obuf[por++] = x | '0';
    memcpy(obuf + por, out + outi + 4, 96 - outi);
    por += 96 - outi;
}

template <typename T> void wt_real(T x) {
    ostringstream oss;
    oss << fixed << setprecision(15) << double(x);
    string s = oss.str();
    wt(s);
}

void wt(int x) {
    wt_integer(x);
}
void wt(ll x) {
    wt_integer(x);
}
void wt(i128 x) {
    wt_integer(x);
}
void wt(uint x) {
    wt_integer(x);
}
void wt(ull x) {
    wt_integer(x);
}
void wt(u128 x) {
    wt_integer(x);
}
void wt(double x) {
    wt_real(x);
}
void wt(long double x) {
    wt_real(x);
}

template <class T, class U> void wt(const pair<T, U> val) {
    wt(val.first);
    wt(' ');
    wt(val.second);
}
template <size_t N = 0, typename T> void wt_tuple(const T t) {
    if constexpr (N < std::tuple_size<T>::value) {
        if constexpr (N > 0) {
            wt(' ');
        }
        const auto x = std::get<N>(t);
        wt(x);
        wt_tuple<N + 1>(t);
    }
}
template <class... T> void wt(tuple<T...> tpl) {
    wt_tuple(tpl);
}
template <class T, size_t S> void wt(const array<T, S> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}
template <class T> void wt(const vector<T> val) {
    auto n = val.size();
    for (size_t i = 0; i < n; i++) {
        if (i)
            wt(' ');
        wt(val[i]);
    }
}

void print() {
    wt('\n');
}
template <class Head, class... Tail> void print(Head &&head, Tail &&...tail) {
    wt(head);
    if (sizeof...(Tail))
        wt(' ');
    print(forward<Tail>(tail)...);
}
void __attribute__((destructor)) _d() {
    flush();
}
} // namespace fastio


using fastio::flush;
using fastio::print;
using fastio::read;

inline void first(bool i = true) {
    print(i ? "first" : "second");
}
inline void Alice(bool i = true) {
    print(i ? "Alice" : "Bob");
}
inline void Takahashi(bool i = true) {
    print(i ? "Takahashi" : "Aoki");
}
inline void yes(bool i = true) {
    print(i ? "yes" : "no");
}
inline void Yes(bool i = true) {
    print(i ? "Yes" : "No");
}
inline void No() {
    print("No");
}
inline void YES(bool i = true) {
    print(i ? "YES" : "NO");
}
inline void NO() {
    print("NO");
}
inline void Yay(bool i = true) {
    print(i ? "Yay!" : ":(");
}
inline void Possible(bool i = true) {
    print(i ? "Possible" : "Impossible");
}
inline void POSSIBLE(bool i = true) {
    print(i ? "POSSIBLE" : "IMPOSSIBLE");
}

/**
 * @brief Fast IO
 */

struct Poly {
    ll P, Q, R;
};

int main() {
while(1) {
    int N, M;
    cin >> N >> M;
    if (N == 0 && M == 0) return 0;
    M--;
    vector<ll> A(M), X(M);
    rep(i,0,M) cin >> A[i] >> X[i], X[i]--;
    ll B;
    cin >> B;
    vector<Poly> C(N+1);
    rep(i,0,N+1) C[i].P = C[i].Q = C[i].R = 0;
    rep(i,0,M) {
        int L = max(0, (int)X[i]-(int)sqrt(A[i])), R = min((int)N,(int)X[i]+(int)sqrt(A[i])+1);
        C[L].P += -1, C[L].Q += X[i] * 2, C[L].R += A[i] - X[i] * X[i];
        C[R].P -= -1, C[R].Q -= X[i] * 2, C[R].R -= A[i] - X[i] * X[i];
    }
    rep(i,0,N) C[i+1].P += C[i].P, C[i+1].Q += C[i].Q, C[i+1].R += C[i].R;
    vector<ll> H(N);
    rep(i,0,N) H[i] = C[i].P * (ll)i * (ll)i + C[i].Q * (ll)i + C[i].R;
    ll OK = 0, NG = 1LL<<50;
    while(NG - OK > 1) {
        ll MID = (OK + NG) / 2;
        vector<int> COUNT(N+1,0);
        rep(i,0,N) {
            if (MID <= H[i]) {
                COUNT[0]++, COUNT[N]--;
                continue;
            }
            ll D = MID - H[i];
            if (B < D) continue;
            ll E = sqrt(B - D);
            COUNT[max(0LL,(ll)i-E)]++, COUNT[min((ll)N,(ll)i+E+1)]--;
        }
        rep(i,0,N) COUNT[i+1] += COUNT[i];
        bool check = false;
        rep(i,0,N) if (COUNT[i] == N) check = true;
        if (check) OK = MID;
        else NG = MID;
    }
    cout << OK << endl;
}
}
accuracy: 1
time_ms: 610
memory_kb: 39704
final_rank: 10

code_snippet: #ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <type_traits>
#include <typeindex>
#include <unordered_map>
#include <unordered_set>

#endif
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(v) v.begin(), v.end()
template <class T, class U>
inline bool chmax(T& a, U b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T, class U>
inline bool chmin(T& a, U b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
constexpr int INF = 1001001001;
constexpr int64_t llINF = 3000000000000000000;

template <class S, S (*op)(S, S), S (*e)()>
struct dual_segtree {
    int sz = 1, log = 0;
    vector<S> lz;
    dual_segtree(vector<S> a) {
        int n = a.size();
        while (sz < n) {
            sz <<= 1;
            log++;
        }
        lz.assign(sz << 1, e());
        for (int i = 0; i < n; i++) lz[i + sz] = a[i];
    }
    void push(int k) {
        int b = __builtin_ctz(k);
        for (int d = log; d > b; d--) {
            lz[k >> d << 1] = op(lz[k >> d << 1], lz[k >> d]);
            lz[k >> d << 1 | 1] = op(lz[k >> d << 1 | 1], lz[k >> d]);
            lz[k >> d] = e();
        }
    }
    void apply(int l, int r, S x) {
        l += sz, r += sz;
        push(l);
        push(r);
        while (l < r) {
            if (l & 1) {
                lz[l] = op(lz[l], x);
                l++;
            }
            if (r & 1) {
                r--;
                lz[r] = op(lz[r], x);
            }
            l >>= 1, r >>= 1;
        }
    }
    S get(int k) {
        k += sz;
        S res = e();
        while (k) {
            res = op(res, lz[k]);
            k >>= 1;
        }
        return res;
    }
};

struct S {
    ll a, b, c;
};
S op(S a, S b) { return S{a.a + b.a, a.b + b.b, a.c + b.c}; }
S e() { return S{0, 0, 0}; }
ll min_left(ll x, ll a) {
    int ng = x - a - 1, ok = x;
    while (ok - ng > 1) {
        int m = (ok + ng) / 2;
        if ((x - m) * (x - m) <= a)
            ok = m;
        else
            ng = m;
    }
    return ok;
}
void solve() {
    int n, m;
    cin >> n >> m;
    if (n == 0 && m == 0) exit(0);
    vector<int> a(m), x(m);
    rep(i, m - 1) {
        cin >> a[i] >> x[i];
        x[i]--;
    }
    cin >> a[m - 1];
    dual_segtree<S, op, e> seg(vector<S>(n, e()));
    rep(i, m - 1) {
        int k = min_left(x[i], a[i]);
        int l = max(0, k);
        int r = min(n, x[i] * 2 - k + 1);
        // for u:[l,r)
        // add a[i]-x[i]^2-u^2+2ux[i]
        seg.apply(l, r, S{-1, 2 * x[i], a[i] - 1LL * x[i] * x[i]});
    }
    vector<ll> v(n);
    rep(i, n) {
        auto [A, b, c] = seg.get(i);
        v[i] = A * i * i + b * i + c;
    }
    ll ok = 0, ng = *min_element(all(v)) + a.back() + 1;
    while (ng - ok > 1) {
        ll X = (ok + ng) / 2;
        int L = 0, R = n;
        rep(i, n) {
            if (v[i] < X) {
                int l = min_left(i, a.back() + v[i] - X);
                int r = 2 * i - l + 1;
                chmax(L, l);
                chmin(R, r);
            }
        }
        if (L >= R)
            ng = X;
        else
            ok = X;
    }
    cout << ok << endl;
}
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    /*int t;
    cin >> t;
    while (t--) */
    while (1) solve();
}
accuracy: 1
time_ms: 290
memory_kb: 81832
final_rank: 14

code_snippet: #include <bits/stdc++.h>

#include <algorithm>

#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param n `0 <= n`
// @return minimum non-negative `x` s.t. `n <= 2**x`
int ceil_pow2(int n) {
    int x = 0;
    while ((1U << x) < (unsigned int)(n)) x++;
    return x;
}

// @param n `1 <= n`
// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
int bsf(unsigned int n) {
#ifdef _MSC_VER
    unsigned long index;
    _BitScanForward(&index, n);
    return index;
#else
    return __builtin_ctz(n);
#endif
}

}  // namespace internal

}  // namespace atcoder

#include <cassert>
#include <iostream>
#include <vector>
namespace atcoder {

template <class S,
          S (*op)(S, S),
          S (*e)(),
          class F,
          S (*mapping)(F, S),
          F (*composition)(F, F),
          F (*id)()>
struct lazy_segtree {
  public:
    lazy_segtree() : lazy_segtree(0) {}
    lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
        log = internal::ceil_pow2(_n);
        size = 1 << log;
        d = std::vector<S>(2 * size, e());
        lz = std::vector<F>(size, id());
        for (int i = 0; i < _n; i++) d[size + i] = v[i];
        for (int i = size - 1; i >= 1; i--) {
            update(i);
        }
    }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push(r >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;
    std::vector<F> lz;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f) {
        d[k] = mapping(f, d[k]);
        if (k < size) lz[k] = composition(f, lz[k]);
    }
    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = id();
    }
};

}  // namespace atcoder

using namespace atcoder;
using namespace std;

typedef long long int ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;

#define rep(i,a,n) for(ll i = a; i < n; i++)

// 区間sum & 区間等差加算
namespace arithmetic_add {

const ll LINF = ll(4e18);
const int INF = int(1e9) + 10;

struct S {
  ll sum;
  int l, r;
};
struct F {
  ll a, b;
};
S op(S s, S t) { return {s.sum + t.sum, min(s.l, t.l), max(s.r, t.r)}; }
S e() { return {0, INF, -INF}; }
S mapping(F f, S s) {
  return {s.sum + (f.a * (s.l + s.r - 1) + f.b * 2) * (s.r - s.l) / 2, s.l,
          s.r};
}
F composition(F f, F g) { return {f.a + g.a, f.b + g.b}; }
F id() { return {0, 0}; }

using lazy_segtype =
    atcoder::lazy_segtree<S, op, e, F, mapping, composition, id>;

struct lazy_segtree_arithmetic : lazy_segtype {
  using lazy_segtype::lazy_segtype;
  lazy_segtree_arithmetic(int n) {
    vector<S> sv(n);
    for (int i = 0; i < n; i++) sv[i] = {0, i, i + 1};
    (*this) = lazy_segtree_arithmetic(sv);
  }
  lazy_segtree_arithmetic(vector<ll> v) {
    vector<S> sv(v.size());
    for (int i = 0; i < v.size(); i++) sv[i] = {v[i], i, i + 1};
    (*this) = lazy_segtree_arithmetic(sv);
  }
  // f = (a, b)
  // [l, r) に b, a+b, 2a+b, ... を加算
  void apply(int l, int r, F f) {
    lazy_segtype::apply(l, r, {f.a, f.b - f.a * get(l).l});
  }
  void apply(int p, F f) { apply(p, {f.a, f.b - f.a * get(p).l}); }
};
}  // namespace arithmetic_add

using namespace arithmetic_add;

struct S2{
    long long value;
    int size;
};
using F2 = long long;

S2 op(S2 a, S2 b){ return {a.value+b.value, a.size+b.size}; }
S2 e(){ return {0, 0}; }
S2 mapping(F2 f, S2 x){ return {x.value + f*x.size, x.size}; }
F2 composition(F2 f, F2 g){ return f+g; }
F2 id(){ return 0; }

int main(){
    while(true){
        ll n,m;
        cin >> n >> m;
        if(n == 0) break;

        vll a(m), x(m-1);
        rep(i,0,m-1) cin >> a[i] >> x[i];
        cin >> a[m-1];

        lazy_segtree_arithmetic segl(n-1), segr(n-1);
        
        vll asum(n+1); 
        rep(i,0,m-1){
            ll ok = 0, ng = n+1;
            while(abs(ok-ng) > 1){
                ll mid = (ok+ng)/2;
                if(a[i] < mid*mid) ng = mid;
                else ok = mid;
            }
            x[i]--;
            // [max(0, i-ok), i]
            if(max<ll>(0, x[i]-ok) < n-1){
                ll dl = x[i]-max<ll>(0,x[i]-ok);
                segl.apply(max<ll>(0, x[i]-ok), x[i], {2, -2*dl+1});
                if(max<ll>(0, x[i]-ok) > 0) segl.apply(max<ll>(0, x[i]-ok)-1, max<ll>(0, x[i]-ok), {0, dl*dl});
            }
            
            // [i, min(i+ok,n-1)]
            if(x[i] < n-1){
                ll dr = min<ll>(x[i]+ok, n-1) - x[i]; 
                segr.apply(x[i], min<ll>(x[i]+ok, n-1), {-2, -1});
                if(min<ll>(x[i]+ok, n-1) < n-1) segr.apply(min<ll>(x[i]+ok, n-1), min<ll>(x[i]+ok, n-1)+1, {0, dr*dr});
            }

            asum[max<ll>(0, x[i]-ok)] += a[i];
            asum[min(x[i]+ok, n-1) + 1] -= a[i];    
        }

        vll sum(n);
        rep(i,0,n){
            asum[i+1] += asum[i]; 
            sum[i] = segl.prod(i, n-1).sum;
            sum[i] += segr.prod(0,i).sum;
            sum[i] += asum[i];
        }

        ll ok = 0, ng = 1ll << 60;
        while(abs(ok-ng) > 1){
            ll mid = (ok+ng)/2;

            auto check = [&](){
                
                vll memocnt(n+1);
                rep(i,0,n){
                    if(sum[i] >= mid){
                        memocnt.front()++;
                        memocnt.back()--;
                        continue;
                    }

                    ll rem = mid - sum[i];
                    if(rem > a[m-1]) return false;

                    ll ok2 = 0, ng2 = n+1;
                    while(abs(ok2-ng2) > 1){
                        ll mid2 = (ok2+ng2)/2;
                        
                        if(a[m-1] - mid2*mid2 >= rem) ok2 = mid2;
                        else ng2 = mid2;
                    }

                    memocnt[max<ll>(0, i-ok2)]++;
                    memocnt[min(i+ok2+1, n)]--;
                }
                rep(i,0,n){
                    memocnt[i+1] += memocnt[i];
                    if(memocnt[i] == n) return true;
                }
                return false;
            };

            if(check()) ok = mid;
            else ng = mid;
        }

        cout << ok << endl;
    }
}
accuracy: 1
time_ms: 3000
memory_kb: 134192
final_rank: 20

code_snippet: #include <bits/stdc++.h>

#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

#include <algorithm>

#ifdef _MSC_VER
#include <intrin.h>
#endif

namespace atcoder {

namespace internal {

// @param n `0 <= n`
// @return minimum non-negative `x` s.t. `n <= 2**x`
int ceil_pow2(int n) {
    int x = 0;
    while ((1U << x) < (unsigned int)(n)) x++;
    return x;
}

// @param n `1 <= n`
// @return minimum non-negative `x` s.t. `(n & (1 << x)) != 0`
int bsf(unsigned int n) {
#ifdef _MSC_VER
    unsigned long index;
    _BitScanForward(&index, n);
    return index;
#else
    return __builtin_ctz(n);
#endif
}

}  // namespace internal

}  // namespace atcoder

#include <cassert>
#include <iostream>
#include <vector>
namespace atcoder {

template <class S,
          S (*op)(S, S),
          S (*e)(),
          class F,
          S (*mapping)(F, S),
          F (*composition)(F, F),
          F (*id)()>
struct lazy_segtree {
  public:
    lazy_segtree() : lazy_segtree(0) {}
    lazy_segtree(int n) : lazy_segtree(std::vector<S>(n, e())) {}
    lazy_segtree(const std::vector<S>& v) : _n(int(v.size())) {
        log = internal::ceil_pow2(_n);
        size = 1 << log;
        d = std::vector<S>(2 * size, e());
        lz = std::vector<F>(size, id());
        for (int i = 0; i < _n; i++) d[size + i] = v[i];
        for (int i = size - 1; i >= 1; i--) {
            update(i);
        }
    }

    void set(int p, S x) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = x;
        for (int i = 1; i <= log; i++) update(p >> i);
    }

    S get(int p) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        return d[p];
    }

    S prod(int l, int r) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return e();

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push(r >> i);
        }

        S sml = e(), smr = e();
        while (l < r) {
            if (l & 1) sml = op(sml, d[l++]);
            if (r & 1) smr = op(d[--r], smr);
            l >>= 1;
            r >>= 1;
        }

        return op(sml, smr);
    }

    S all_prod() { return d[1]; }

    void apply(int p, F f) {
        assert(0 <= p && p < _n);
        p += size;
        for (int i = log; i >= 1; i--) push(p >> i);
        d[p] = mapping(f, d[p]);
        for (int i = 1; i <= log; i++) update(p >> i);
    }
    void apply(int l, int r, F f) {
        assert(0 <= l && l <= r && r <= _n);
        if (l == r) return;

        l += size;
        r += size;

        for (int i = log; i >= 1; i--) {
            if (((l >> i) << i) != l) push(l >> i);
            if (((r >> i) << i) != r) push((r - 1) >> i);
        }

        {
            int l2 = l, r2 = r;
            while (l < r) {
                if (l & 1) all_apply(l++, f);
                if (r & 1) all_apply(--r, f);
                l >>= 1;
                r >>= 1;
            }
            l = l2;
            r = r2;
        }

        for (int i = 1; i <= log; i++) {
            if (((l >> i) << i) != l) update(l >> i);
            if (((r >> i) << i) != r) update((r - 1) >> i);
        }
    }

    template <bool (*g)(S)> int max_right(int l) {
        return max_right(l, [](S x) { return g(x); });
    }
    template <class G> int max_right(int l, G g) {
        assert(0 <= l && l <= _n);
        assert(g(e()));
        if (l == _n) return _n;
        l += size;
        for (int i = log; i >= 1; i--) push(l >> i);
        S sm = e();
        do {
            while (l % 2 == 0) l >>= 1;
            if (!g(op(sm, d[l]))) {
                while (l < size) {
                    push(l);
                    l = (2 * l);
                    if (g(op(sm, d[l]))) {
                        sm = op(sm, d[l]);
                        l++;
                    }
                }
                return l - size;
            }
            sm = op(sm, d[l]);
            l++;
        } while ((l & -l) != l);
        return _n;
    }

    template <bool (*g)(S)> int min_left(int r) {
        return min_left(r, [](S x) { return g(x); });
    }
    template <class G> int min_left(int r, G g) {
        assert(0 <= r && r <= _n);
        assert(g(e()));
        if (r == 0) return 0;
        r += size;
        for (int i = log; i >= 1; i--) push((r - 1) >> i);
        S sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!g(op(d[r], sm))) {
                while (r < size) {
                    push(r);
                    r = (2 * r + 1);
                    if (g(op(d[r], sm))) {
                        sm = op(d[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(d[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

  private:
    int _n, size, log;
    std::vector<S> d;
    std::vector<F> lz;

    void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }
    void all_apply(int k, F f) {
        d[k] = mapping(f, d[k]);
        if (k < size) lz[k] = composition(f, lz[k]);
    }
    void push(int k) {
        all_apply(2 * k, lz[k]);
        all_apply(2 * k + 1, lz[k]);
        lz[k] = id();
    }
};

}  // namespace atcoder

using namespace atcoder;
using namespace std;

typedef long long int ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;

#define rep(i,a,n) for(ll i = a; i < n; i++)

// 区間sum & 区間等差加算
namespace arithmetic_add {

const ll LINF = ll(4e18);
const int INF = int(1e9) + 10;

struct S {
  ll sum;
  int l, r;
};
struct F {
  ll a, b;
};
S op(S s, S t) { return {s.sum + t.sum, min(s.l, t.l), max(s.r, t.r)}; }
S e() { return {0, INF, -INF}; }
S mapping(F f, S s) {
  return {s.sum + (f.a * (s.l + s.r - 1) + f.b * 2) * (s.r - s.l) / 2, s.l,
          s.r};
}
F composition(F f, F g) { return {f.a + g.a, f.b + g.b}; }
F id() { return {0, 0}; }

using lazy_segtype =
    atcoder::lazy_segtree<S, op, e, F, mapping, composition, id>;

struct lazy_segtree_arithmetic : lazy_segtype {
  using lazy_segtype::lazy_segtype;
  lazy_segtree_arithmetic(int n) {
    vector<S> sv(n);
    for (int i = 0; i < n; i++) sv[i] = {0, i, i + 1};
    (*this) = lazy_segtree_arithmetic(sv);
  }
  lazy_segtree_arithmetic(vector<ll> v) {
    vector<S> sv(v.size());
    for (int i = 0; i < v.size(); i++) sv[i] = {v[i], i, i + 1};
    (*this) = lazy_segtree_arithmetic(sv);
  }
  // f = (a, b)
  // [l, r) に b, a+b, 2a+b, ... を加算
  void apply(int l, int r, F f) {
    lazy_segtype::apply(l, r, {f.a, f.b - f.a * get(l).l});
  }
  void apply(int p, F f) { apply(p, {f.a, f.b - f.a * get(p).l}); }
};
}  // namespace arithmetic_add

using namespace arithmetic_add;

struct S2{
    long long value;
    int size;
};
using F2 = long long;

S2 op(S2 a, S2 b){ return {a.value+b.value, a.size+b.size}; }
S2 e(){ return {0, 0}; }
S2 mapping(F2 f, S2 x){ return {x.value + f*x.size, x.size}; }
F2 composition(F2 f, F2 g){ return f+g; }
F2 id(){ return 0; }

int main(){
    while(true){
        ll n,m;
        cin >> n >> m;
        if(n == 0) break;

        vll a(m), x(m-1);
        rep(i,0,m-1) cin >> a[i] >> x[i];
        cin >> a[m-1];

        lazy_segtree_arithmetic segl(n-1), segr(n-1);
        
        vll asum(n+1); 
        rep(i,0,m-1){
            ll ok = 0, ng = n+1;
            while(abs(ok-ng) > 1){
                ll mid = (ok+ng)/2;
                if(a[i] < mid*mid) ng = mid;
                else ok = mid;
            }
            x[i]--;
            // [max(0, i-ok), i]
            if(max<ll>(0, x[i]-ok) < n-1){
                ll dl = x[i]-max<ll>(0,x[i]-ok);
                segl.apply(max<ll>(0, x[i]-ok), x[i], {2, -2*dl+1});
                if(max<ll>(0, x[i]-ok) > 0) segl.apply(max<ll>(0, x[i]-ok)-1, max<ll>(0, x[i]-ok), {0, dl*dl});
            }
            
            // [i, min(i+ok,n-1)]
            if(x[i] < n-1){
                ll dr = min<ll>(x[i]+ok, n-1) - x[i]; 
                segr.apply(x[i], min<ll>(x[i]+ok, n-1), {-2, -1});
                if(min<ll>(x[i]+ok, n-1) < n-1) segr.apply(min<ll>(x[i]+ok, n-1), min<ll>(x[i]+ok, n-1)+1, {0, dr*dr});
            }

            asum[max<ll>(0, x[i]-ok)] += a[i];
            asum[min(x[i]+ok, n-1) + 1] -= a[i];    
        }

        vll sum(n);
        rep(i,0,n){
            asum[i+1] += asum[i]; 
            sum[i] = segl.prod(i, n-1).sum;
            sum[i] += segr.prod(0,i).sum;
            sum[i] += asum[i];
        }

        ll ok = 0, ng = 1ll << 60;
        while(abs(ok-ng) > 1){
            ll mid = (ok+ng)/2;

            auto check = [&](){
                
                vll memocnt(n+1);
                rep(i,0,n){
                    if(sum[i] >= mid){
                        memocnt.front()++;
                        memocnt.back()--;
                        continue;
                    }

                    ll rem = mid - sum[i];
                    if(rem > a[m-1]) return false;

                    ll ok2 = 0, ng2 = n+1;
                    while(abs(ok2-ng2) > 1){
                        ll mid2 = (ok2+ng2)/2;
                        
                        if(a[m-1] - mid2*mid2 >= rem) ok2 = mid2;
                        else ng2 = mid2;
                    }

                    memocnt[max<ll>(0, i-ok2)]++;
                    memocnt[min(i+ok2+1, n)]--;
                }
                rep(i,0,n){
                    memocnt[i+1] += memocnt[i];
                    if(memocnt[i] == n) return true;
                }
                return false;
            };

            if(check()) ok = mid;
            else ng = mid;
        }

        cout << ok << endl;
    }
}
accuracy: 1
time_ms: 2860
memory_kb: 134152
final_rank: 19

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
using ll = long long;
#define all(p) p.begin(),p.end()
template<class T> bool chmin(T &a, T b){return (a > b ? a = b, 1 : 0);}
template<class T> bool chmax(T &a, T b){return (a < b ? a = b, 1 : 0);}

ll my_sqrt(ll a){
    ll l = 0, r = (1 << 30);
    while (r - l > 1){
        ll m = (l + r) / 2;
        if (m * m <= a) l = m;
        else r = m;
    }
    return l;
}

void solve(int N, int M){
    vector<ll> A(N + 1), p1(N + 1), p2(N + 1);
    rep(i, 0, M - 1){
        ll a, x;
        cin >> a >> x;
        x--;
        ll z = my_sqrt(a);
        ll l = x - z;
        ll r = x + z + 1;
        if (l < 0) l = 0;
        if (r > N) r = N;
        A[l] += a - x * x;
        A[r] -= a - x * x;
        p2[l] -= 1;
        p2[r] += 1;
        p1[l] += 2 * x;
        p1[r] -= 2 * x;
    }
    ll AM;
    cin >> AM;
    rep(i, 0, N){
        A[i + 1] += A[i];
        p2[i + 1] += p2[i];
        p1[i + 1] += p1[i];
        A[i] += p2[i] * (ll)(i) * i;
        A[i] += p1[i] * i;
    }
    ll ansL = 0, ansR = ((ll)(M) << 30);
    while (ansR - ansL > 1){
        ll mid = (ansL + ansR) / 2;
        ll L = 0, R = N;
        rep(i, 0, N){
            if (A[i] >= mid) continue;
            if (AM + A[i] < mid){
                R = -1;
                break;
            }
            ll a = my_sqrt(AM + A[i] - mid);
            chmax(L, i - a);
            chmin(R, i + a + 1);
        }
        if (L < R) ansL = mid;
        else ansR = mid;
    }
    cout << ansL << "\n";
}

int main(){
    int N, M;
    while (cin >> N >> M, N) solve(N, M);
}
accuracy: 1
time_ms: 180
memory_kb: 26724
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll= long long;
using vll=vector<ll>;
#define elif else if

#define repname(a, b, c, d, e, ...) e
#define rep(...)                    repname(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)
#define rep0(x)                     for (int rep_counter = 0; rep_counter < (x); ++rep_counter)
#define rep1(i, x)                  for (int i = 0; i < (x); ++i)
#define rep2(i, l, r)               for (int i = (l); i < (r); ++i)
#define rep3(i, l, r, c)            for (int i = (l); i < (r); i += (c))
#define all(A) A.begin(),A.end()

struct ScalarInput {
    template<class T>
    operator T(){
        T ret;
        cin >> ret;
        return ret;
    }
};
struct VectorInput {
    size_t n;
    VectorInput(size_t n): n(n) {}
    template<class T>
    operator vector<T>(){
        vector<T> ret(n);
        for(T &x : ret) cin >> x;
        return ret;
    }
};
ScalarInput input(){ return ScalarInput(); }
VectorInput input(size_t n){ return VectorInput(n); }

template<typename T>
void print(vector<T> a){
  for(int i=0;i<a.size();i++){
    cout<<a[i]<<" \n"[i+1==a.size()];
  }
}

template<class T>
void print(T x){
    cout << x << '\n';
}
 
template <class Head, class... Tail>
void print(Head&& head, Tail&&... tail){
  cout << head << ' ';
  print(forward<Tail>(tail)...);
}

// change min, change max
template<class T>
bool chmin(T &a, const T &b) {if (a > b) {a = b; return 1;} return 0;}
template<class T>
bool chmax(T &a, const T &b) {if (a < b) {a = b; return 1;} return 0;}


// pragma
// #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")

bool is_end = false;

ll sqrtz(ll N) {
    ll L = 0;
    ll R = sqrt(N) + 10000;
    while (abs(R - L) > 1) {
        ll mid = (R + L) / 2;
        if (mid * mid <= N)L = mid;
        else R = mid;
    }
    return L;
}

void solve(ll N,ll M)
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  vll A(M,0),X(M,0);
  vll BL(N,0),BR(N,0),F(N,0),CL(N,0),CR(N,0);
  vll L(M,0),R(M,0);

  vector<vll> f(N,vll(3,0));
  rep(i,M){
    cin>>A[i];
    if(i==M-1)break;
    cin>>X[i];
    X[i]--;
    ll d=sqrtz(A[i]);
    L[i]=X[i]-d;
    R[i]=X[i]+d;
    f[max(L[i],0ll)][2]+=-1;
    f[max(L[i],0ll)][1]+=2*X[i];
    f[max(L[i],0ll)][0]+=A[i]-X[i]*X[i];

    if(R[i]+1<N){
      f[R[i]+1][2]-=-1;
      f[R[i]+1][1]-=2*X[i];
      f[R[i]+1][0]-=A[i]-X[i]*X[i];
    }
    
  }
  rep(i,N-1){
    rep(j,3)f[i+1][j]+=f[i][j];
  }
  vll D(N,0);
  rep(i,N){
    D[i]=f[i][0]+f[i][1]*i+f[i][2]*i*i;
  }

  // rep(i,N){
  //   cout<<D[i]<<" \n"[i==N-1];
  // }



  ll ok=0,ng=1e18;
  while(abs(ng-ok)>1){
    ll mid=(ok+ng)/2;
    ll LE=0,RI=N-1;
    rep(i,N){
      ll d=mid-D[i];
      if(d<=0){
        continue;
      }
      else if(d>A[M-1]){
        LE=1e18;
      }

      ll z=sqrtz(A[M-1]-d);
      LE=max(LE,i-z);
      RI=min(RI,z+i);

    }
    if(LE<=RI)ok=mid;
    else ng=mid;
  }

  cout<<ok<<endl;




  return;
}

int main()
{
  ll N,M;
  while (cin>>N>>M)
  {
    if(N+M==0)return 0;
    solve(N,M);
    
  }

  return 0;
}
accuracy: 1
time_ms: 1490
memory_kb: 107832
final_rank: 17

code_snippet: #include <bits/stdc++.h>
using namespace std;

using ll= long long;
using vll=vector<ll>;
#define elif else if

#define repname(a, b, c, d, e, ...) e
#define rep(...)                    repname(__VA_ARGS__, rep3, rep2, rep1, rep0)(__VA_ARGS__)
#define rep0(x)                     for (int rep_counter = 0; rep_counter < (x); ++rep_counter)
#define rep1(i, x)                  for (int i = 0; i < (x); ++i)
#define rep2(i, l, r)               for (int i = (l); i < (r); ++i)
#define rep3(i, l, r, c)            for (int i = (l); i < (r); i += (c))
#define all(A) A.begin(),A.end()

struct ScalarInput {
    template<class T>
    operator T(){
        T ret;
        cin >> ret;
        return ret;
    }
};
struct VectorInput {
    size_t n;
    VectorInput(size_t n): n(n) {}
    template<class T>
    operator vector<T>(){
        vector<T> ret(n);
        for(T &x : ret) cin >> x;
        return ret;
    }
};
ScalarInput input(){ return ScalarInput(); }
VectorInput input(size_t n){ return VectorInput(n); }

template<typename T>
void print(vector<T> a){
  for(int i=0;i<a.size();i++){
    cout<<a[i]<<" \n"[i+1==a.size()];
  }
}

template<class T>
void print(T x){
    cout << x << '\n';
}
 
template <class Head, class... Tail>
void print(Head&& head, Tail&&... tail){
  cout << head << ' ';
  print(forward<Tail>(tail)...);
}

// change min, change max
template<class T>
bool chmin(T &a, const T &b) {if (a > b) {a = b; return 1;} return 0;}
template<class T>
bool chmax(T &a, const T &b) {if (a < b) {a = b; return 1;} return 0;}


// pragma
// #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")

bool is_end = false;

ll sqrtz(ll N) {
    ll L = 0;
    ll R = sqrt(N) + 10000;
    while (abs(R - L) > 1) {
        ll mid = (R + L) / 2;
        if (mid * mid <= N)L = mid;
        else R = mid;
    }
    return L;
}

void solve(ll N,ll M)
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  vll A(M,0),X(M,0);
  vll BL(N,0),BR(N,0),F(N,0),CL(N,0),CR(N,0);
  vll L(M,0),R(M,0);

  vector<vll> f(N,vll(3,0));
  rep(i,M){
    cin>>A[i];
    if(i==M-1)break;
    cin>>X[i];
    X[i]--;
    ll d=sqrtz(A[i]);
    L[i]=X[i]-d;
    R[i]=X[i]+d;
    f[max(L[i],0ll)][2]+=-1;
    f[max(L[i],0ll)][1]+=2*X[i];
    f[max(L[i],0ll)][0]+=A[i]-X[i]*X[i];

    if(R[i]+1<N){
      f[R[i]+1][2]-=-1;
      f[R[i]+1][1]-=2*X[i];
      f[R[i]+1][0]-=A[i]-X[i]*X[i];
    }
    
  }
  rep(i,N-1){
    rep(j,3)f[i+1][j]+=f[i][j];
  }
  vll D(N,0);
  rep(i,N){
    D[i]=f[i][0]+f[i][1]*i+f[i][2]*i*i;
  }

  // rep(i,N){
  //   cout<<D[i]<<" \n"[i==N-1];
  // }



  ll ok=0,ng=1e18;
  while(abs(ng-ok)>1){
    ll mid=(ok+ng)/2;
    ll LE=0,RI=N-1;
    rep(i,N){
      ll d=mid-D[i];
      if(d<=0){
        continue;
      }
      else if(d>A[M-1]){
        LE=1e18;
      }

      ll z=sqrtz(A[M-1]-d);
      LE=max(LE,i-z);
      RI=min(RI,z+i);

    }
    if(LE<=RI)ok=mid;
    else ng=mid;
  }

  cout<<ok<<endl;




  return;
}

int main()
{
  ll N,M;
  while (cin>>N>>M)
  {
    if(N+M==0)return 0;
    solve(N,M);
    
  }

  return 0;
}
accuracy: 1
time_ms: 1510
memory_kb: 107936
final_rank: 18

code_snippet: #include <bits/stdc++.h>

std::vector<int> SQ(40000);

template <class T>
void out(std::vector<T> A) {
    for (auto x : A) std::cout << x << ' ';
    std::cout << std::endl;
}

bool solve() {
    int N, M;
    // N = mt() % 10 + 1;
    // M = mt() % 5 + 1;
    // std::cout << N << ' ' << M << std::endl;
    std::cin >> N >> M;
    if (N == 0 and M == 0) return false;
    std::vector<long long> L(N), R(N), C(N + 1);
    // std::vector<long long> SS(N);
    for (int i{} ; i < M - 1 ; i++) {
        int A, X;
        // A = mt() % 30 + 1;
        // X = mt() % N + 1;
        // std::cout << A << ' ' << X << std::endl;
        std::cin >> A >> X;
        X--;
        int d{(int)std::distance(SQ.begin(), std::upper_bound(SQ.begin(), SQ.end(), A))};
        assert(d >= 2);
        if (X + 1 < N) R[X + 1]++;
        if (X - 1 >= 0) L[X - 1]++;
        if (X + 2 < N) R[X + 2]++;
        if (X - 2 >= 0) L[X - 2]++;
        if (X + d < N) R[X + d] -= SQ[d];
        if (X - d >= 0) L[X - d] -= SQ[d];
        if (X + d + 1 < N) R[X + d + 1] += (long long)2 * SQ[d - 1] + 2 * (d - 1) - 1;
        if (X - d - 1 >= 0) L[X - d - 1] += (long long)2 * SQ[d - 1] + 2 * (d - 1) - 1;
        if (X + d + 2 < N) R[X + d + 2] -= SQ[d - 1];
        if (X - d - 2 >= 0) L[X - d - 2] -= SQ[d - 1];
        C[std::max(0, X - d + 1)] += A;
        C[std::min(N, X + d)] -= A;

        // for (int j{} ; j < N ; j++) {
        //     SS[j] += std::max(0LL, A - (long long)(j - X) * (j - X));
        // }
    }
    // out(L);
    for (int i{1} ; i < N + 1 ; i++) {
        C[i] += C[i - 1];
    }
    for (int i{} ; i < 3 ; i++) {
        for (int j{1} ; j < N ; j++) {
            R[j] += R[j - 1];
        }
        for (int j{N - 2} ; j >= 0 ; j--) {
            L[j] += L[j + 1];
        }
        // out(L);
    }
    std::vector<long long> S(N);
    for (int i{} ; i < N ; i++) S[i] = C[i] - L[i] - R[i];
    // out(S);
    int AM;
    // AM = mt() % 30 + 1;
    // std::cout << AM << std::endl;
    std::cin >> AM;
    auto getRange{[&](long long f, long long t, int i) -> std::pair<int, int> {
        assert(f < t);
        if (f + AM < t) {
            return { -1, -1 };
        }
        int ok{}, ng{N + 1};
        while (ng - ok > 1) {
            int mid{ok + (ng - ok) / 2};
            long long v{std::max(0LL, AM - (long long)mid * mid)};
            if (f + v >= t) {
                ok = mid;
            }
            else {
                ng = mid;
            }
        }
        return { std::max(0, i - ok), std::min(N, i + ok + 1) };
    }};
    long long ok{}, ng{(long long)1e15};
    while (ng - ok > 1) {
        long long mid{ok + (ng - ok) / 2};
        int l{}, r{N};
        for (int i{} ; i < N ; i++) {
            if (S[i] >= mid) continue;
            auto [ll, rr]{getRange(S[i], mid, i)};
            if (ll == -1 and rr == -1) {
                l = 100;
                r = -1;
                break;
            }
            l = std::max(ll, l);
            r = std::min(rr, r);
        }
        if (l < r) {
            ok = mid;
        }
        else {
            ng = mid;
        }
    }
    std::cout << ok << '\n';
    // std::cout << "---------------------" << std::endl;
    return true;
}

int main() {
    std::cin.tie(nullptr)->sync_with_stdio(false);
    for (int i{} ; i < 40000 ; i++) {
        SQ[i] = i * i;
    }
    while (solve()) ;
}
accuracy: 1
time_ms: 190
memory_kb: 34688
final_rank: 8

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "main.cpp"

i64 solve(int N, int M) {
    vector<i64> A(N, 0), B(N, 0), C(N, 0);
    for(int i : rep(M - 1)) {
        i64 a = in(), x = in(); x--;
        i64 d = floor(sqrtl(a));
        if(x + 1 < N) A[x + 1] += 1;
        if(x + 2 < N) A[x + 2] += 1;
        if(x + d + 1 < N) A[x + d + 1] -= (d + 1) * (d + 1);
        if(x + d + 2 < N) A[x + d + 2] += (d + 1) * (d + 1) + d * d - 2;
        if(x + d + 3 < N) A[x + d + 3] -= d * d;

        if(0 <= x - 1) B[x - 1] += 1;
        if(0 <= x - 2) B[x - 2] += 1;
        if(0 <= x - d - 1) B[x - d - 1] -= (d + 1) * (d + 1);
        if(0 <= x - d - 2) B[x - d - 2] += (d + 1) * (d + 1) + d * d - 2;
        if(0 <= x - d - 3) B[x - d - 3] -= d * d;

        C[max(x - d, 0LL)] += a;
        if(x + d + 1 < N) C[x + d + 1] -= a;
    }

    for(int _ : rep(3)) for(int i :    rep(N - 1)) A[i + 1] += A[i];
    for(int _ : rep(3)) for(int i : revrep(N - 1)) B[i] += B[i + 1];
    for(int _ : rep(1)) for(int i :    rep(N - 1)) C[i + 1] += C[i];
    vector<i64> D(N);
    for(int i : rep(N)) D[i] = C[i] - A[i] - B[i];

    i64 E = in();

    i64 ok = 0, ng = 1e18;
    while(ng - ok > 1) {
        i64 X = (ok + ng) / 2;

        bool check = [&] {
            i64 L = 0, R = N - 1;
            for(int i : rep(N)) if(D[i] < X) {
                if(D[i] + E < X) return false;
                i64 p = floor(sqrtl(D[i] + E - X));
                chmax(L, i64(i) - p);
                chmin(R, i64(i) + p);
            }
            return L <= R;
        }();

        (check ? ok : ng) = X;
    }
    return ok;
}

int main() {
    while(true) {
        int N = in(), M = in();
        if(make_pair(N, M) == make_pair(0, 0)) return 0;
        print(solve(N, M));
    }
}
accuracy: 1
time_ms: 170
memory_kb: 34528
final_rank: 5

code_snippet: #include<bits/stdc++.h>
using namespace std;

using ll = long long;
using ld = long double;

ll INF = 1e18;
bool is_end = false;

bool isOK(ll mid, const vector<ll> &defense, ll a)
{
    ll N = defense.size();
    vector<ll> diff(N, 0);
    for (int i = 0; i < N; ++i)
    {
        diff[i] = max(0LL, mid - defense[i]);
    }
    
    vector<ll> L(N), R(N);
    for (int i = 0; i < N; ++i)
    {
        ll d = diff[i];
        if (d > a) return false;
        
        if (d == 0)
        {
            L[i] = -INF;
            R[i] = INF;
        }
        else
        {
            ll w = sqrt((ld)(a - d));
            L[i] = max(0LL, i - w);
            R[i] = min(N-1, i + w);
        }
    }
    
    ll maxL = *max_element(L.begin(), L.end());
    ll minR = *min_element(R.begin(), R.end());
    
    return maxL <= minR;
}

void solve()
{
    ll N, M; cin >> N >> M;
    
    if (N == 0 && M == 0)
    {
        is_end = true;
        return;
    }
    
    vector<ll> A(M), X(M);
    for (int i = 0; i < M-1; ++i)
    {
        ll a, x; cin >> a >> x;
        x -= 1;
        A[i] = a, X[i] = x;
    }
    {
        int i = M-1;
        ll a; cin >> a;
        A[i] = a, X[i] = -1;
    }
    
    vector<ll> defense(N, 0);
    vector< pair<ll, tuple<ll, ll, ll>> > vec;
    for (int i = 0; i < M-1; ++i)
    {
        ll a = A[i], x = X[i];
        ll w = sqrt((ld)a);
        ll left = max(0LL, x - w), right = min(N, x + w + 1);
        
        assert(w * w <= a && a < (w + 1) * (w + 1));
        
        vec.push_back({ left, {a - x * x, 2 * x, -1} });
        vec.push_back({ right, {- a + x * x, -2 * x, 1} });
        // cout << left << " " << right << endl;
    }
    sort(vec.begin(), vec.end());
    
    {
        ll a = 0, b = 0, c = 0;
        ll id = 0;
        for (int i = 0; i < N; ++i)
        {
            while (id < (ll)vec.size())
            {
                auto [pos, tup] = vec[id];
                if (i < pos) break;
                
                auto [na, nb, nc] = tup;
                a += na, b += nb, c += nc;
                
                id++;
            }
            
            defense[i] = (a + b * i + c * i * i);
        }
    }
    
    // for (int i = 0; i < N; ++i)
    // {
    //     cout << defense[i] << " ";
    // }
    // cout << endl;
    
    ll ok = *min_element(defense.begin(), defense.end());
    ll ng = 1e18;
    
    // cout << ok << " " << ng << endl;
    
    while (abs(ok - ng) > 1)
    {
        ll mid = (ok + ng) / 2;
        
        if (isOK(mid, defense, A[M-1])) ok = mid;
        else ng = mid;
    }
    cout << ok << endl;
    
    
    return;
}

int main()
{
    while (!is_end)
    {
        solve();
    }
    
    return 0;
}
accuracy: 1
time_ms: 1310
memory_kb: 43396
final_rank: 16

code_snippet: #include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,s,t) for (int i = (int)(s); i < (int)(t); ++i)
#define all(x) (x).begin(), (x).end()

int main(){
    while(true){
        int N,M;
        cin>>N>>M;
        if(N==0)break;
        vector<ll> val(N);
        rep(i,0,M-1){
            ll a;
            int x;
            cin>>a>>x;
            --x;
            val[x]+=a;
            for(ll y=1;a-y*y>0&&(x-y>=0 || x+y<N);++y){
                if (x-y>=0)val[x-y] += a-y*y;
                if (x+y<N) val[x+y] += a-y*y;
            }
        }
        ll a;
        cin>>a;
        ll lb = *min_element(all(val)), ub = 1e15;
        while(ub-lb>1){
            ll m = (lb+ub)/2;

            bool ok = true;
            int minright = N, maxleft = -1;
            rep(i,0,N){
                if(val[i]>=m)continue;
                if (val[i]+a-m<0){
                    ok=false;
                    break;
                }
                ll s = sqrt(val[i]+a-m);
                while((s+1)*(s+1)<=val[i]+a-m)++s;
                maxleft=max(maxleft,i-(int)s);
                minright=min(minright,i+(int)s);
                if(minright<maxleft){
                    ok=false;
                }
            }
            if(!ok){
                ub=m;
            }else{
                lb=m;
            }
        }
        cout<<lb<<endl;
    }
}
accuracy: 1
time_ms: 1780
memory_kb: 11180
final_rank: 12