Problem:
Problem I:
Beautiful Spacing
Text is a sequence of words, and a word consists of characters. Your task is to put words into a grid with
W
columns and sufficiently many lines. For the beauty of the layout, the following conditions have to be satisfied.
The words in the text must be placed keeping their original order. The following figures show correct and incorrect layout examples for a 4 word text "This is a pen" into 11 columns.
Figure I.1: A good layout.
Figure I.2: BAD | Do not reorder words.
Between two words adjacent in the same line, you must place at least one space character. You sometimes have to put more than one space in order to meet other conditions.
Figure I.3: BAD | Words must be separated by spaces.
A word must occupy the same number of consecutive columns as the number of characters in it. You cannot break a single word into two or more by breaking it into lines or by inserting spaces.
Figure I.4: BAD | Characters in a single word must be contiguous.
The text must be justified to the both sides. That is, the first word of a line must startfrom the first column of the line, and except the last line, the last word of a line must end at the last column.
Figure I.5: BAD | Lines must be justied to both the left and the right sides.
The text is the most beautifully laid out when there is no unnecessarily long spaces. For instance, the layout in Figure I.6 has at most 2 contiguous spaces, which is more beautiful than that in Figure I.1, having 3 contiguous spaces. Given an input text and the number of columns, please find a layout such that the length of the longest contiguous spaces between words is minimum.
Figure I.6: A good and the most beautiful layout.
Input
The input consists of multiple datasets, each in the following format.
W N
x
1
x
2
...
x
N
W
,
N
, and
x
i
are all integers.
W
is the number of columns (3 ≤
W
≤ 80,000).
N
is the number of words (2 ≤
N
≤ 50,000).
x
i
is the number of characters in the
i
-th word (1 ≤
x
i
≤ (
W
−1)/2 ). Note that the upper bound on
x
i
assures that there always exists a layout satisfying the conditions.
The last dataset is followed by a line containing two zeros.
Output
For each dataset, print the smallest possible number of the longest contiguous spaces between words.
Sample Input
11 4
4 2 1 3
5 7
1 1 1 2 2 1 2
11 7
3 1 3 1 3 3 4
100 3
30 30 39
30 3
2 5 3
0 0
Output for the Sample Input
2
1
2
40
1

Submitted solutions:

code_snippet: //#include<CSpreadSheet.h>

#include<iostream>
#include<cmath>
#include<cstdio>
#include<sstream>
#include<cstdlib>
#include<string>
#include<string.h>
#include<cstring>
#include<algorithm>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<ctime>
#include<bitset>
#include<cmath>
#define eps 1e-6
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define ll __int64
#define LL long long
#define lson l,m,(rt<<1)
#define rson m+1,r,(rt<<1)|1
#define M 1000000007
//#pragma comment(linker, "/STACK:1024000000,1024000000")
using namespace std;

#define Maxn 51000

bool dp[Maxn];
int n,w;
LL sum[Maxn];

bool iscan(int m)
{
    if(sum[n]+n-1<=w)
        return true;

    memset(dp,0,sizeof(dp));
    dp[0]=1;
    int la=0;

    for(int i=0;i<=n-2;i++)
    {
        if(!dp[i])
            continue;
        for(int j=max(i+1,la+1);j<=n;j++)
        {
            if(sum[j]-sum[i]+j-i-1>w)
                break;
            if(sum[j]-sum[i]+(j-i-1)*m<w)
                continue;
            dp[j]=true;
            la=j;
            if(sum[n]-sum[j]+n-j-1<=w)
                return true;
        }
    }
    return false;
}
int main()
{
    //freopen("in.txt","r",stdin);
   //freopen("out.txt","w",stdout);
   while(scanf("%d%d",&w,&n)&&w+n)
   {
       sum[0]=0;
       for(int i=1;i<=n;i++)
       {
           LL temp;
           scanf("%lld",&temp);
           sum[i]=sum[i-1]+temp;
       }
       int l=1,r=w,m,ans;

       while(l<=r)
       {
           m=(l+r)>>1;
           if(iscan(m))
           {
               ans=m;
               r=m-1;
           }
           else
                l=m+1;
       }
       printf("%d\n",ans);
   }
    return 0;
}
accuracy: 1
time_ms: 460
memory_kb: 4008
final_rank: 2

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...);
}

/**
 * @brief template
 */

template<typename T>struct BIT{
    int n; T all=0; vector<T> val;
    BIT(int _n=0):n(_n),val(_n+10){}
    void clear(){val.assign(n+10,0); all=T();}
    void add(int i,T x){
        for(i++;i<=n;i+=(i&-i))val[i]=val[i]+x;
        all+=x;
    }
    T sum(int i){
        T res=0;
        for(;i;i-=(i&-i))res+=val[i];
        return res;
    }
    T sum(int L,int R){return sum(R)-sum(L);} // [L,R)

    int lower_bound(T x){
        int ret=0,len=1;
        while(2*len<=n)len<<=1;
        for(;len>=1;len>>=1){
            if(ret+len<=n and val[ret+len]<x){
                ret+=len;
                x-=val[ret];
            }
        }
        return ret;
    }
};

/**
 * @brief Binary Indexed Tree
 */

int main() {
while(1) {
    ll M, N;
    cin >> M >> N;
    if (N == 0) return 0;
    vector<ll> X(N);
    rep(i,0,N) cin >> X[i];
    vector<ll> XS(N+1,0);
    rep(i,0,N) XS[i+1] = XS[i] + X[i];
    auto Calc = [&](int L, int R, ll Len) -> ll {
        return XS[R] - XS[L] + Len*(R-L-1);
    };
    auto Judge = [&](ll Len) -> bool {
        BIT<ll> Seg(N);
        Seg.add(0,1);
        rep(i,1,N) {
            int NG = -1, OK = i;
            while(OK - NG > 1) {
                int MID = (OK + NG) / 2;
                if (Calc(MID,i,1LL) <= M) OK = MID;
                else NG = MID;
            }
            int Left = OK;
            OK = -1, NG = i;
            while(NG - OK > 1) {
                int MID = (OK + NG) / 2;
                if (Calc(MID,i,Len) >= M) OK = MID;
                else NG = MID;
            }
            int Right = OK;
            if (Seg.sum(Left, Right+1) >= 1) Seg.add(i,1);
        }
        {
            int NG = -1, OK = N;
            while(OK - NG > 1) {
                int MID = (OK + NG) / 2;
                if (Calc(MID,N,1LL) <= M) OK = MID;
                else NG = MID;
            }
            if (Seg.sum(OK,N) >= 1) return true;
            else return false;
        }
    };
    {
        int OK = M, NG = 0;
        while(OK - NG > 1) {
            int MID = (OK + NG) / 2;
            if (Judge(MID)) OK = MID;
            else NG = MID;
        }
        cout << OK << endl;
    }
}
}
accuracy: 1
time_ms: 6710
memory_kb: 4268
final_rank: 18

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

#define rep(i, n) for (int i = 0; i < (n); i++)
#define per(i, n) for (int i = (n)-1; i >= 0; i--)
#define rep2(i, l, r) for (int i = (l); i < (r); i++)
#define per2(i, l, r) for (int i = (r)-1; i >= (l); i--)
#define each(e, x) for (auto &e : x)
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) rbegin(x), rend(x)
#define eb emplace_back
#define MM << ' ' <<
#define TT template <typename T>
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

TT bool chmin(T &x, T y) { return x > y ? (x = y, true) : false; }
TT bool chmax(T &x, T y) { return x < y ? (x = y, true) : false; }

TT using minheap = priority_queue<T, vector<T>, greater<T>>;
TT using maxheap = priority_queue<T>;

TT void print(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << (i == n - 1 ? '\n' : ' ');
    if (n == 0) cout << '\n';
}

TT void printn(vector<T> v, T x = 0) {
    int n = sz(v);
    rep(i, n) cout << v[i] + x << '\n';
}

TT void rearrange(vector<T> &v) {
    sort(all(v));
    v.erase(unique(all(v)), end(v));
}

TT int lb(vector<T> &v, T x) { return lower_bound(all(v), x) - begin(v); }
TT int ub(vector<T> &v, T x) { return upper_bound(all(v), x) - begin(v); }

const int inf = (1 << 30) - 1;
const ll INF = (1LL << 60) - 1;

struct io_setup {
    io_setup() {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout << fixed << setprecision(15);
    }
} io_setup;

int main() {
    while (1) {
        int w, n;
        cin >> w >> n;
        if (!w)
            break;
        vector<int> x(n);
        rep(i, n) cin >> x[i];
        vector<ll> sum(n + 1, 0);
        rep(i, n) sum[i + 1] = sum[i] + x[i];
        auto check1 = [&](int l, int r) {
            return sum[r] - sum[l] + r - l - 1 <= w;
        };
        auto check2 = [&](int l, int r, ll k) {
            return sum[r] - sum[l] + k * (r - l - 1) < w;
        };
        int ok = w, ng = 0;
        while (abs(ok - ng) > 1) {
            int mid = (ok + ng) / 2;
            vector<int> dp(n + 2, 0);
            dp[0] = 1, dp[1] = -1;
            int idx1 = 0, idx2 = 0;
            bool f = false;
            rep(i, n) {
                if (i)
                    dp[i] += dp[i - 1];
                while (idx1 < n + 1 && check1(i, idx1)) idx1++;
                while (idx2 < n + 1 && check2(i, idx2, mid)) idx2++;
                if (dp[i]) {
                    if (idx1 == n + 1)
                        f = true;
                    else
                        dp[idx2]++, dp[idx1]--;
                }
            }
            (f ? ok : ng) = mid;
        }
        cout << ok << '\n';
    }
}
accuracy: 1
time_ms: 610
memory_kb: 3960
final_rank: 3

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

using namespace std;
using ll = long long;

bool is_end = false;

template< typename Monoid >
struct SegmentTree {
	using F = function< Monoid(Monoid, Monoid) >;

	int sz;
	vector< Monoid > seg;

	const F f;
	const Monoid M1;

	SegmentTree(int n, const F f, const Monoid &M1) : f(f), M1(M1) {
		sz = 1;
		while(sz < n) sz <<= 1;
		seg.assign(2 * sz, M1);
	}

	void set(int k, const Monoid &x) {
		seg[k + sz] = x;
	}

	void build() {
		for(int k = sz - 1; k > 0; k--) {
			seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
		}
	}

	void update(int k, const Monoid &x) {
		k += sz;
		seg[k] = x;
		while(k >>= 1) {
			seg[k] = f(seg[2 * k + 0], seg[2 * k + 1]);
		}
	}

	Monoid query(int a, int b) {
		Monoid L = M1, R = M1;
		for(a += sz, b += sz; a < b; a >>= 1, b >>= 1) {
			if(a & 1) L = f(L, seg[a++]);
			if(b & 1) R = f(seg[--b], R);
		}
		return f(L, R);
	}

	Monoid operator[](const int &k) const {
		return seg[k + sz];
	}
	
};

ll op(ll a, ll b) {return max(a, b);}
ll e = 0;

bool isOK(ll mid, ll W, vector<ll> &A)
{
	ll N = A.size();
	
	vector<ll> lower(N+1, 0), upper(N+1, 0);
	for (int i = 0; i < N; ++i)
	{
		lower[i+1] = lower[i] + A[i] + 1;
		upper[i+1] = upper[i] + A[i] + mid;
	}
	
	ll lst = 0;
	SegmentTree<ll> seg(N+1, op, e);
	seg.update(0, 1);
	
	// cerr << mid << endl;
	for (ll i = 1; i <= N; ++i)
	{
		auto itrl = lower_bound(lower.begin(), lower.end(), lower[i] - (W + 1));
		ll mn = itrl - lower.begin();
		auto itru = upper_bound(upper.begin(), upper.end(), upper[i] - (W + mid));
		ll mx = itru - upper.begin() - 1;
		
		mx = min(mx, i-2);
		if (mx < 0) continue;
		
		ll res = seg.query(mn, mx+1);
		seg.update(i, res);
		if (res > 0) {lst = i;}
		// cerr << i << ": " << mx << " " << mn << " " << res << endl;
	}
	
	return lower[N] - lower[lst] <= W + 1;
}


void calc()
{
	ll W, N; cin >> W >> N;
	
	if (W == 0 && N == 0)
	{
		is_end = true;
		return;
	}
	
	vector<ll> A(N);
	for (int i = 0; i < N; ++i) {cin >> A[i];}
	
	ll ng = 0, ok = W;
	while (abs(ok - ng) > 1)
	{
		ll mid = (ok + ng) / 2;
		if (isOK(mid, W, A)) ok = mid;
		else ng = mid;
	}
	
	cout << ok << endl;
	
	return;
}

int main()
{
	while (!is_end)
	{
		calc();
	}
	
	return 0;
}
accuracy: 1
time_ms: 7660
memory_kb: 5208
final_rank: 20

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int w,n;
    while(cin >> w >> n,n){
        vector<int> x(n);
        vector<ll> sum(n+1);
        for(int i=0;i<n;i++){
            cin >> x[i];
            sum[i+1] = sum[i]+x[i];
        }
        auto slv = [&](ll mid)->bool{
            vector<int> dp(n+2);
            dp[0] = 1; dp[1] = -1;
            for(int i=0;i<n;i++){
                dp[i+1] += dp[i];
                if(!dp[i]) continue;
                int l = i, r = n;
                while(r-l>1){
                    int m = (l+r)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(ll)(m-i)*mid >= w){
                        r = m;
                    }
                    else{
                        l = m;
                    }
                }
                if(r == n) return true;
                if(sum[r+1]-sum[i]+(r-i) > w) continue;
                int nl = r, nr = n;
                while(nr-nl>1){
                    int m = (nl+nr)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(m-i) <= w){
                        nl = m;
                    }
                    else{
                        nr = m;
                    }
                }
                // [r,nl]
                dp[r+1]++;
                dp[nl+2]--;
                if(nl+1 == n) return true; // 枝刈り
            }
            return dp[n];
        };
        int l = 0, r = w;
        while(r-l>1){
            int mid = (l+r)/2;
            if(slv(mid)){
                r = mid;
            }
            else{
                l = mid;
            }
        }
        cout << r << "\n";
    }
}
accuracy: 1
time_ms: 4160
memory_kb: 3876
final_rank: 10

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int w,n;
    while(cin >> w >> n,n){
        vector<int> x(n);
        vector<ll> sum(n+1);
        for(int i=0;i<n;i++){
            cin >> x[i];
            sum[i+1] = sum[i]+x[i];
        }
        auto slv = [&](ll mid)->bool{
            vector<int> dp(n+2);
            dp[0] = 1; dp[1] = -1;
            for(int i=0;i<n;i++){
                dp[i+1] += dp[i];
                if(!dp[i]) continue;
                { // 枝刈り
                    ll s = sum[n]-sum[i];
                    if(s+(ll)(n-1-i)*mid < w) return true;
                }
                int l = i, r = n;
                while(r-l>1){
                    int m = (l+r)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(ll)(m-i)*mid >= w){
                        r = m;
                    }
                    else{
                        l = m;
                    }
                }
                // if(r == n) return true;
                if(sum[r+1]-sum[i]+(r-i) > w) continue;
                int nl = r, nr = n;
                while(nr-nl>1){
                    int m = (nl+nr)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(m-i) <= w){
                        nl = m;
                    }
                    else{
                        nr = m;
                    }
                }
                // [r,nl]
                dp[r+1]++;
                dp[min(n+1,nl+2)]--;
            }
            return dp[n];
        };
        int l = 0, r = w;
        while(r-l>1){
            int mid = (l+r)/2;
            if(slv(mid)){
                r = mid;
            }
            else{
                l = mid;
            }
        }
        cout << r << "\n";
    }
}
accuracy: 1
time_ms: 4220
memory_kb: 3960
final_rank: 12

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int w,n;
    while(cin >> w >> n,n){
        vector<int> x(n);
        vector<ll> sum(n+1);
        for(int i=0;i<n;i++){
            cin >> x[i];
            sum[i+1] = sum[i]+x[i];
        }
        auto slv = [&](ll mid)->bool{
            vector<int> dp(n+2);
            dp[0] = 1; dp[1] = -1;
            for(int i=0;i<n;i++){
                dp[i+1] += dp[i];
                if(!dp[i]) continue;
                int l = i, r = n;
                while(r-l>1){
                    int m = (l+r)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(ll)(m-i)*mid >= w){
                        r = m;
                    }
                    else{
                        l = m;
                    }
                }
                if(r == n) return true;
                if(sum[r+1]-sum[i]+(r-i) > w) continue;
                int nl = r, nr = n;
                while(nr-nl>1){
                    int m = (nl+nr)/2;
                    ll s = sum[m+1]-sum[i];
                    if(s+(m-i) <= w){
                        nl = m;
                    }
                    else{
                        nr = m;
                    }
                }
                // [r,nl]
                dp[r+1]++;
                dp[min(n+1,nl+2)]--;
            }
            return dp[n];
        };
        int l = 0, r = w;
        while(r-l>1){
            int mid = (l+r)/2;
            if(slv(mid)){
                r = mid;
            }
            else{
                l = mid;
            }
        }
        cout << r << "\n";
    }
}
accuracy: 1
time_ms: 4170
memory_kb: 3876
final_rank: 11

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

#define int long long

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using int128_t = __int128_t;
#define repa(i, n) for(int i = 0; i < n; ++ i)
#define repb(i, a, b) for(int i = a; i < b; ++ i)
#define repc(i, a, b, c) for(int i = a; i < b; i += c)
#define overload4(a, b, c, d, e, ...) e
#define overload3(a, b, c, d, ...) d
#define rep(...) overload4(__VA_ARGS__, repc, repb, repa)(__VA_ARGS__)
#define rep1a(i, n) for(int i = 0; i <= n; ++ i)
#define rep1b(i, a, b) for(int i = a; i <= b; ++ i)
#define rep1c(i, a, b, c) for(int i = a; i <= b; i += c)
#define rep1(...) overload4(__VA_ARGS__, rep1c, rep1b, rep1a)(__VA_ARGS__)
#define rev_repa(i, n) for(int i=n-1;i>=0;i--)
#define rev_repb(i, a, b) assert(a > b);for(int i=a;i>b;i--)
#define rev_rep(...) overload3(__VA_ARGS__, rev_repb, rev_repa)(__VA_ARGS__)
#define rev_rep1a(i, n) for(int i=n;i>=1;i--)
#define rev_rep1b(i, a, b) assert(a >= b);for(int i=a;i>=b;i--)
#define rev_rep1(...) overload3(__VA_ARGS__, rev_rep1b, rev_rep1a)(__VA_ARGS__)
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define eb emplace_back
#define fr first
#define sc second
#define all(c) c.begin(),c.end()
#define rall(c) c.rbegin(), c.rend()
#define lb(c, x) distance((c).begin(), lower_bound(all(c), (x)))
#define ub(c, x) distance((c).begin(), upper_bound(all(c), (x)))
#define Sort(a) sort(all(a))
#define Rev(a) reverse(all(a))
#define Uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define si(c) (int)(c).size()
inline ll popcnt(ull a){ return __builtin_popcountll(a); }
#define kth_bit(x, k) ((x>>k)&1)
#define unless(A) if(!(A))
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll intpow(ll a, ll b, ll m) {ll ans = 1; while(b){ if(b & 1) (ans *= a) %= m; (a *= a) %= m; b /= 2; } return ans; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template <class T> using vc = vector<T>;
template <class T> using vvc = vector<vc<T>>;
template <class T> using vvvc = vector<vvc<T>>;
template <class T> using vvvvc = vector<vvvc<T>>;
template <class T> using pq = priority_queue<T>;
template <class T> using pqg = priority_queue<T, vector<T>, greater<T>>;
template <class T, class U> using umap = unordered_map<T, U>;
template<class T> void scan(T& a){ cin >> a; }
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){ scan(head); in(tail...); }
void print(){ cout << ' '; }
template<class T> void print(const T& a){ cout << a; }
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ cout << ' '; print(*i); } }
int out(){ cout << '\n'; return 0; }
template<class T> int out(const T& t){ print(t); cout << '\n'; return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); cout << ' '; out(tail...); return 0; }
#define CHOOSE(a) CHOOSE2 a
#define CHOOSE2(a0,a1,a2,a3,a4,x,...) x
#define debug_1(x1) cout<<#x1<<": "<<x1<<endl
#define debug_2(x1,x2) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<endl
#define debug_3(x1,x2,x3) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<endl
#define debug_4(x1,x2,x3,x4) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<endl
#define debug_5(x1,x2,x3,x4,x5) cout<<#x1<<": "<<x1<<", "#x2<<": "<<x2<<", "#x3<<": "<<x3<<", "#x4<<": "<<x4<<", "#x5<<": "<<x5<<endl
#ifdef DEBUG
#define debug(...) CHOOSE((__VA_ARGS__,debug_5,debug_4,debug_3,debug_2,debug_1,~))(__VA_ARGS__)
#define dump(...) { print(#__VA_ARGS__); print(":"); out(__VA_ARGS__); }
#else
#define debug(...)
#define dump(...)
#endif

struct io_setup {
    io_setup(int precision = 20) {
        ios::sync_with_stdio(false);
        cin.tie(0);
        cout << fixed << setprecision(precision);
    }
} io_setup_ {};

void solve() {
    int w, n;
    while(cin >> w >> n) {
        if(w == 0 && n == 0) break;
        VEC(int, x, n);
        vc<int> sum(n + 1, 0);
        rep(i, n) {
            sum[i + 1] = sum[i] + x[i];
        }
        auto check = [&](int len) -> bool {
            debug(len);
            vc<int> dp(n + 2, 0);
            dp[0] = 1;
            dp[1] = -1;
            rep(i, n) {
                if(i - 1 >= 0) dp[i] += dp[i - 1];
                if(dp[i] == 0) continue;
                debug(i, dp[i]);
                // debug(i, sum[n] - sum[i] + (n - i - 1));
                if(sum[n] - sum[i] + (n - i - 1) <= w) return true;
                int ok = i + 2, ng = n;
                auto ck1 = [&](int id) -> bool {
                    // debug(i, id, sum[id] - sum[i] + id - i - 1);
                    return sum[id] - sum[i] + (id - i - 1) <= w;
                };
                while(ng - ok > 1) {
                    int mid = (ok + ng) / 2;
                    if(ck1(mid)) ok = mid;
                    else ng = mid;
                }
                debug(i, ok);
                int mx = ok;
                ng = i + 1;
                auto ck2 = [&](int id) -> bool {
                    if(sum[id] - sum[i] > w) return false;
                    // (w - (sum[id] - sum[i])) / (id - i - 1) <= len
                    return len * (id - i - 1) >= w - (sum[id] - sum[i]);
                };
                if(!ck2(mx)) continue;
                while(ok - ng > 1) {
                    int mid = (ok + ng) / 2;
                    if(ck2(mid)) ok = mid;
                    else ng = mid;
                }
                debug(i, ok, mx);
                dp[ok] ++;
                dp[mx + 1] --;
            }
            return false;
        };
        int ok = w, ng = 0;
        while(ok - ng > 1) {
            int mid = (ok + ng) / 2;
            if(check(mid)) ok = mid;
            else ng = mid;
        }
        out(ok);
    }
}

signed main() {
    int testcase = 1;
    // in(testcase);
    while(testcase--) solve();
    return 0;
}
accuracy: 1
time_ms: 3030
memory_kb: 4296
final_rank: 9

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 revrep(i, t, s) for (int i = (int)(t)-1; i >= (int)(s); --i)
#define all(x) begin(x), end(x)
template <typename T> bool chmax(T& a, const T& b) { return a < b ? (a = b, 1) : 0; }
template <typename T> bool chmin(T& a, const T& b) { return a > b ? (a = b, 1) : 0; }

template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
    for (int i = 0; i < (int) v.size(); ++i) os << v[i] << " ";
    return os;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(15);

    while (true) {
        int W, N;
        cin >> W >> N;
        if (W == 0) break;
        vector<ll> x(N);
        for (auto& y : x) cin >> y;
        x.push_back(1e9);
        int lb = 0, ub = W;
        while (ub - lb > 1) {
            int m = (lb + ub) / 2;
            vector<int> reachable(N+2);
            ll small = x[0] + m, big = x[0] + 1;
            int j = 0, k = 0;
            reachable[0] = 1;
            reachable[1] = -1;
            bool ok = true;

            rep(i,0,N) {
                while (j < N && small < W+m) {
                    small += x[++j] + m;
                }
                while (k < N && big <= W+1) {
                    big += x[++k] + 1;
                }
                if (reachable[i] && min(j+1, N) < k+1) {
                    ++reachable[min(j+1, N)];
                    --reachable[k+1];
                }
                small -= x[i] + m;
                big -= x[i] + 1;
                reachable[i+1] += reachable[i];
            }
            if (reachable[N]) {
                ub = m;
            } else {
                lb = m;
            }
        }
        cout << ub << "\n";
    }
}
accuracy: 1
time_ms: 540
memory_kb: 4164
final_rank: 5

code_snippet: /*	author:  Kite_kuma
	created: 2022.03.01 15:08:03 */

// #ifdef LOCAL
// #define _GLIBCXX_DEBUG
// #endif
#include <bits/stdc++.h>
using namespace std;

#pragma region macros

#define foa(s, v) for(auto &s : v)
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define popcnt(n) __builtin_popcountll((long long)n)

#define REPname(a, b, c, d, e, ...) e
#define rep(...) REPname(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define REP0(x) for(int Counter_in_rep_macro = 0; Counter_in_rep_macro < (x); ++Counter_in_rep_macro)
#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 DREPname(a, b, c, d, e, ...) e
#define drep(...) DREPname(__VA_ARGS__, DREP3, DREP2, DREP1)(__VA_ARGS__)
#define DREP1(i, x) for(int i = (x)-1; i >= 0; --i)
#define DREP2(i, l, r) for(int i = (r)-1; i >= (l); --i)
#define DREP3(i, l, r, c) for(int i = (r)-1; i >= (l); i -= (c))

#pragma endregion

#pragma region aliases

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = std::vector<int>;
using vvi = std::vector<std::vector<int>>;
using vvvi = std::vector<std::vector<std::vector<int>>>;
using vll = std::vector<ll>;
using vvll = std::vector<vll>;
using vvvll = std::vector<vvll>;
using pii = std::pair<int, int>;
using pll = std::pair<long long, long long>;
template <class T = ll>
using V = std::vector<T>;
template <class T = ll>
using VV = V<V<T>>;
template <class T = ll>
using VVV = V<V<V<T>>>;
template <class T = ll>
using pqup = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <class T = ll>
using pqdn = std::priority_queue<T>;

#pragma endregion

#pragma region constants

const int inf = 1e9;
const long long INF = 1e18;
const long double pi = acos(-1);
const char dl = '\n';
const char sp = ' ';
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

const int mod_1000000007 = 1000000007;
const int mod_998244353 = 998244353;

#pragma endregion

#pragma region basic_operation

template <class T0, class T1, class T2>
inline bool in_range(T0 x, T1 lef, T2 rig) {
	return ((lef <= x) && (x < rig));
}

template <class T>
inline bool chmin(T &a, T b) {
	if(a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmax(T &a, T b) {
	if(a < b) {
		a = b;
		return true;
	}
	return false;
}

void Yes(bool f = 1) { std::cout << (f ? "Yes" : "No") << '\n'; }
void No() { std::cout << "No\n"; }
void YES(bool f = 1) { std::cout << (f ? "YES" : "NO") << '\n'; }
void NO() { std::cout << "NO\n"; }

template <class T>
void drop(T answer) {
	std::cout << answer << '\n';
	exit(0);
}

void err(bool flag = true) {
	if(!flag) return;
	std::cout << -1 << '\n';
	exit(0);
}

template <class T>
void vout(std::vector<T> const &v, bool vertically = 0) {
	if(vertically) {
		for(auto const &a : v) {
			std::cout << a << '\n';
		}
		return;
	}
	for(auto it = v.begin(); it != v.end(); it++) {
		std::cout << (*it);
		if(it != v.end() - 1) {
			std::cout << ' ';
		}
	}
	std::cout << '\n';
	return;
}

inline void print() { std::cout << '\n'; }
template <class T>
inline void print(T x) {
	std::cout << x << '\n';
	return;
}
template <typename Head, typename... Tail>
void print(Head H, Tail... T) {
	std::cout << H << " ";
	print(T...);
}

template <class T>
void add(std::vector<T> &v, T val) {
	for(auto &a : v) a += val;
	return;
}

template <class T>
T dup(T a, T b) {
	assert(b != 0);
	return (a + b - 1) / b;
}

template <class T>
T greatest_lower_multiple(T x, T d) {
	if(d == 0) return 0;
	if(d < 0) d *= -1;
	T y = x % d;
	if(y < 0) y += d;
	return x - y;
}

template <class T>
T least_upper_multiple(T x, T d) {
	return -greatest_lower_multiple(-x, d);
}

long long POW(long long a, long long n) {
	long long res = 1;
	while(n > 0) {
		if(n & 1) res = res * a;
		a = a * a;
		n >>= 1;
	}
	return res;
}

long long modpow(long long a, long long n, long long mod) {	 // a^n mod
	assert(n >= 0 && mod);
	if(mod == 1) return 0LL;
	long long res = 1;
	a %= mod;
	while(n > 0) {
		if(n & 1) res = res * a % mod;
		a = a * a % mod;
		n >>= 1;
	}
	return res < 0 ? res + mod : res;
}

// return x which satisfies a * x % mod == gcd(a, mod)
// not (mod | a)
long long modinv(long long a, long long mod) {
	long long b = mod, u = 1, v = 0;
	while(b) {
		long long t = a / b;
		a -= t * b;
		std::swap(a, b);
		u -= t * v;
		std::swap(u, v);
	}
	u %= mod;
	if(u < 0) u += mod;
	return u;
}

template <class T>
int lb(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::lower_bound(a.begin(), a.end(), x));
}
template <class T>
int ub(const std::vector<T> &a, const T x) {
	return std::distance(a.begin(), std::upper_bound(a.begin(), a.end(), x));
}
template <class T>
void unq_sort(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<int> press(std::vector<T> &a) {
	auto vec = a;
	unq_sort(vec);
	std::vector<int> ret;
	for(auto &v : a) ret.push_back(lb(vec, v));
	return ret;
}

#pragma endregion

#pragma region input
#define VEC(type, name, size) \
	vector<type> name(size);  \
	scanner::INPUT(name)
#define VVEC(type, name, h, w)                     \
	vector<vector<type>> name(h, vector<type>(w)); \
	scanner::INPUT(name)
#define INT(...)     \
	int __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
	long long __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define STR(...)        \
	string __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define CHR(...)      \
	char __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define DBL(...)        \
	double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
	long double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define TPL3(type0, type1, type2, name)   \
	std::tuple<type0, type1, type2> name; \
	scanner::INPUT(name);
#define TPL4(type0, type1, type2, type3, name)   \
	std::tuple<type0, type1, type2, type3> name; \
	scanner::INPUT(name);

namespace scanner {
template <class T>
void scan(T &a) {
	std::cin >> a;
}

template <class T, class L>
void scan(std::pair<T, L> &p) {
	scan(p.first);
	scan(p.second);
}

template <class T0, class T1, class T2>
void scan(std::tuple<T0, T1, T2> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	scan(t0);
	scan(t1);
	scan(t2);
	p = std::make_tuple(t0, t1, t2);
}

template <class T0, class T1, class T2, class T3>
void scan(std::tuple<T0, T1, T2, T3> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	T3 t3;
	scan(t0);
	scan(t1);
	scan(t2);
	scan(t3);
	p = std::make_tuple(t0, t1, t2, t3);
}

template <class T>
void scan(std::vector<T> &a) {
	for(auto &i : a) scan(i);
}

void INPUT() {}
template <class Head, class... Tail>
void INPUT(Head &head, Tail &... tail) {
	scan(head);
	INPUT(tail...);
}
}  // namespace scanner

template <typename T1, typename T2>
std::istream &operator>>(std::istream &is, std::pair<T1, T2> &p) {
	is >> p.first >> p.second;
	return is;
}
#pragma endregion

#pragma region debug

#pragma region output
template <typename T1, typename T2>
std::ostream &std::operator<<(std::ostream &os, const std::pair<T1, T2> &p) {
	os << p.first << " " << p.second;
	return os;
}
template <class T>
std::ostream &std::operator<<(std::ostream &os, const std::vector<T> &v) {
	for(int i = 0; i < (int)v.size(); i++) {
		if(i) os << " ";
		os << v[i];
	}
	return os;
}
#pragma endregion

#pragma region view

namespace viewer {
void view(const long long e) {
	if(e == INF)
		std::cerr << "INF";
	else if(e == -INF)
		std::cerr << "-INF";
	else
		std::cerr << e;
}

void view(const int e) {
	if(e == inf)
		std::cerr << "inf";
	else if(e == -inf)
		std::cerr << "-inf";
	else
		std::cerr << e;
}

template <typename T>
void view(const T e) {
	std::cerr << e;
}

template <typename T, typename U>
void view(const std::pair<T, U> &p) {
	std::cerr << "(";
	view(p.first);
	std::cerr << ", ";
	view(p.second);
	std::cerr << ")";
}

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ")";
}

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p) {
	std::cerr << "(";
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ", ";
	view(std::get<3>(p));
	std::cerr << ")";
}

template <typename T>
void view(const std::set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::unordered_set<T> &s) {
	if(s.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(auto &t : s) {
		view(t);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<T> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << "{ ";
	for(const auto &e : v) {
		view(e);
		std::cerr << ", ";
	}
	std::cerr << "\b\b }";
}

template <typename T>
void view(const std::vector<std::vector<T>> &vv) {
	std::cerr << "{\n";
	for(const auto &v : vv) {
		std::cerr << "\t";
		view(v);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v) {
	std::cerr << "{\n";
	for(const auto &c : v) {
		std::cerr << "\t(";
		view(c.first);
		std::cerr << ", ";
		view(c.second);
		std::cerr << ")\n";
	}
	std::cerr << "}";
}

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v) {
	if(v.empty()) {
		std::cerr << "{ }";
		return;
	}
	std::cerr << '{';
	for(const auto &t : v) {
		std::cerr << "\n\t";
		view(t);
		std::cerr << ",";
	}
	std::cerr << "\n}";
}

template <typename T, typename U>
void view(const std::map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m) {
	std::cerr << "{\n";
	for(const auto &t : m) {
		std::cerr << "\t[";
		view(t.first);
		std::cerr << "] : ";
		view(t.second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}
}  // namespace viewer

#pragma endregion

// when debugging : g++ foo.cpp -DLOCAL
#ifdef LOCAL
void debug_out() {}
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
	viewer::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "\b\b]\n";                                   \
	} while(0)
#define dump(x)                                      \
	do {                                             \
		std::cerr << __LINE__ << " " << #x << " : "; \
		viewer::view(x);                             \
		std::cerr << '\n';                           \
	} while(0)

#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

#pragma endregion

#pragma region fenwick_tree

template <class T = long long>
struct binary_indexed_tree {
	std::vector<T> data;
	int n;
	int pw2 = 1;
	binary_indexed_tree(const int &sz) : data(sz + 1, 0), n(sz) {
		while(pw2 << 1 <= n) pw2 <<= 1;
	}
	void add(const int &place, const T &val, const int &index = 0) {
		for(int x = place + 1 - index; x <= n; x += x & -x) data[x] += val;
	}

	// [0, a)
	const T sum0(const int &a, const int &index = 0) const {
		T ret = 0;
		for(int x = a - index; x > 0; x -= x & -x) ret += data[x];
		return ret;
	}

	// [0, b)
	const T sum(const int &a, const int &b, const int &index = 0) const { return sum0(b, index) - sum0(a, index); }

	// point get
	const T get(const int &idx) const { return sum(idx, idx + 1, 0); }
	const T operator[](const int &idx) const { return get(idx); }

	void update(const int &place, const T &val, const int &index = 0) {
		add(place, val + sum0(place, index) - sum0(place + 1, index), index);
	}

	/*
		constraints: for all $i, data[i] >= 0
		returns $i which satisfies:
			start <= i,
			sum[start, i-1) < val <= \sum_[start, i)
		sum[start, n+1) := infinity, sum[start, start-1] := -infinity
	*/
	const int lower_bound(T val, const int &start = 0) const {
		if(val <= 0) return start;
		val += sum0(start);
		int x = 0;
		for(int k = pw2; k > 0; k >>= 1) {
			if(x + k <= n && data[x + k] < val) {
				val -= data[x + k];
				x += k;
			}
		}
		return x + 1;
	}

	/*
		constraints: for all $i, data[i] >= 0
		returns $i which satisfies:
			start <= i,
			sum[start, i-1) <= val < \sum_[start, i) .
		sum[start, n+1) := infinity, sum[start, start-1] := -infinity
	*/
	const int upper_bound(T val, const int &start = 0) const {
		if(val < 0) return start;
		val += sum0(start);
		int x = 0;
		for(int k = pw2; k > 0; k >>= 1) {
			if(x + k <= n && data[x + k] <= val) {
				val -= data[x + k];
				x += k;
			}
		}
		return x + 1;
	}

	void print() const {
#ifdef LOCAL
		std::cerr << "{ ";
		for(int i = 0; i < n; i++) {
			std::cerr << get(i) << (i == n - 1 ? " }\n" : ", ");
		}
#endif
	}
};

#pragma endregion

int solve(int w) {
	int n;
	cin >> n;
	VEC(int, lens, n);
	// binary_indexed_tree<ll> len_sum(n);
	// rep(i, n) len_sum.add(i, ll(lens[i]));

	auto bs = [](int ok, int ng, auto is_ok) -> int {
		while(abs(ok - ng) > 1) {
			int mid = (ok + ng) / 2;
			(is_ok(mid) ? ok : ng) = mid;
		}
		return ok;
	};

	auto judge = [&](int maxspacelength) -> bool {
		// vector<int> dp(n);
		// dp.front() = 1;
		// auto len_minimum = [&](int lef, int rig) -> ll {
		// 	assert(lef-\\ \\< rig);
		// 	return len_sum.s\um(lef, rig, 0) + ll(rig - lef - 1);
		// };
		// auto len_maximum = [&](int lef, int rig) {
		// 	assert(lef < rig);
		// 	return len_sum.sum(lef, rig) + ll(rig - lef - 1) * maxspacelength;
		// };

		binary_indexed_tree<int> dp(n);
		dp.add(0, 1);
		int nxt = 1;
		// auto traceable = [&](int from) {
		// 	ll maxlen = len_maximum(from, nxt);
		// 	return maxlen >= ll(w);
		// };
		// auto packable = [&](int from) {
		// 	ll minilen = len_minimum(from, nxt);
		// 	return minilen <= ll(w);
		// };

		int left = 0;
		int right = 0;
		// left = right = lens.front();
		ll minlensum = -1;
		ll maxlensum = -maxspacelength;
		int sum = 0;
		for(; nxt <= n; nxt++) {
			debug(left, right, nxt, maxspacelength);
			minlensum += 1 + lens[nxt - 1];
			maxlensum += maxspacelength + lens[nxt - 1];
			debug(minlensum, maxlensum);
			while(minlensum > w) {
				debug(left);
				minlensum -= lens[left] + 1;
				// sum -= dp[left++];
				left++;
			}
			if(nxt == n) return dp.sum(left, n);
			// maxlensum += maxspacelength + lens[nxt];
			while(maxlensum >= w && right + 1 < nxt) {
				debug(right);
				maxlensum -= maxspacelength + lens[right];
				// sum += dp[right++];
				right++;
			}

			debug(left, right);

			// if(nxt == n - 1) break;
			// int left = bs(nxt - 1, -1, packable);
			// int right = bs(-1, nxt, traceable);
			// if(right == nxt - 1) right--;
			if(right < left) continue;
			// int righttemp = right;
			// if(right == nxt ) righttemp--;
			sum = dp.sum(left, right);
			if(sum > 0) dp.add(nxt, 1);
		}
		// left = bs(n, -1, packable);
		return bool(dp.sum(left, n));
	};

	return bs(w + 10, 0, judge);
}

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	std::cout << std::fixed << std::setprecision(15);
	srand((unsigned)time(NULL));

	int w;
	while(cin >> w && w) {
		cout << solve(w) << dl;
	}

	return 0;
}
accuracy: 1
time_ms: 1600
memory_kb: 3620
final_rank: 4

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

#define rep(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define ALL(v) (v).begin(),(v).end()
using ll=long long int;
const int inf = 0x3fffffff; const ll INF = 0x1fffffffffffffff; const double eps=1e-12;
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;}



int main(){
    int W,n;
    while(cin>>W>>n){
        if(n==0)break;
        vector<int> a(n);
        rep(i,0,n)cin>>a[i];
        vector<int> rui(n+1);
        rep(i,0,n)rui[i+1]=rui[i]+a[i];

        auto ok1=[&](int L,int R)->bool{
            return rui[R+1]-rui[L]+R-L<=W;
        };
        auto ok2=[&](int L,int R,int x)->bool{
            return rui[R+1]-rui[L]+(R-L)*x>=W;
        };
        auto check=[&](int x)->bool{
            if(ok1(0,n-1))return true;
            vector<int> dp(n+1);
            dp[0]=1;
            int sum=0,ok=0,ng=0;
            rep(i,0,n){
                while(ng<=i and !ok1(ng,i)){
                    if(dp[ng])sum--;
                    ng++;
                }
                while(ok<=i and ok2(ok,i,x)){
                    if(dp[ok])sum++;
                    ok++;
                }
                if(sum){
                    dp[i+1]=1;
                    if(ok1(i+1,n-1))return true;
                }
            }
            return false;
        };

        int L=0,R=W;
        while(R-L>1){
            int mid=(L+R)>>1;
            if(check(mid))R=mid;
            else L=mid;
        }
        cout<<R<<'\n';
    }
    return 0;
}
accuracy: 1
time_ms: 830
memory_kb: 3664
final_rank: 1

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

using namespace std;

#define eps 1e-9
#define INF 2000000000              // 2e9
#define LLINF 2000000000000000000ll // 2e18 (llmax:9e18)
#define all(x) (x).begin(), (x).end()
#define sq(x) ((x) * (x))

#define rep(i, x) for (int i = 0; i < (int)(x); i++)
#define drep(i, x) for (int i = ((int)(x)-1); i >= 0; i--)

#define popcount __builtin_popcount
#define next __next
#define prev __prev

#ifndef LOCAL
#define dmp(...) ;
#else
#define dmp(...)                                                               \
  cerr << "[ " << #__VA_ARGS__ << " ] : " << dump_str(__VA_ARGS__) << endl
#endif

// ---------------- Utility ------------------

template <class T>
bool chmin(T &a, const T &b) {
  if (a <= b) return false;
  a = b;
  return true;
}

template <class T>
bool chmax(T &a, const T &b) {
  if (a >= b) return false;
  a = b;
  return true;
}

template <class T>
using MaxHeap = priority_queue<T>;

template <class T>
using MinHeap = priority_queue<T, vector<T>, greater<T>>;

template <class T>
vector<T> vect(int len, T elem) {
  return vector<T>(len, elem);
}

// ----------------- Input -------------------

template <class T, class U>
istream &operator>>(istream &is, pair<T, U> &p) {
  return is >> p.first >> p.second;
}

template <class T>
istream &operator>>(istream &is, vector<T> &vec) {
  for (int i = 0; i < vec.size(); i++) is >> vec[i];
  return is;
}

// ----------------- Output ------------------

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  return os << p.first << ',' << p.second;
}

template <class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (const T &e : v) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const deque<T> &d) {
  for (const T &e : d) os << e << " ";
  return os;
}

template <class T>
ostream &operator<<(ostream &os, const set<T> &s) {
  os << "{ ";
  for (const T &e : s) os << e << " ";
  return os << "}";
}

template <class T, class U>
ostream &operator<<(ostream &os, const map<T, U> &m) {
  os << "{ ";
  for (const auto &[key, val] : m) os << "( " << key << " -> " << val << " ) ";
  return os << "}";
}

template <class TupleTy, size_t... I>
void dump_tuple(ostream &os, const TupleTy t, std::index_sequence<I...>) {
  (..., (os << (I == 0 ? "" : ",") << std::get<I>(t)));
}

template <class... Args>
ostream &operator<<(ostream &os, const tuple<Args...> &t) {
  os << "(";
  dump_tuple(os, t, std::make_index_sequence<sizeof...(Args)>());
  return os << ")";
}

void dump_str_rec(ostringstream &) {}

template <class Head, class... Tail>
void dump_str_rec(ostringstream &oss, Head &&head, Tail &&... tail) {
  oss << ", " << head;
  dump_str_rec(oss, forward<Tail>(tail)...);
}

template <class T, class... U>
string dump_str(T &&arg, U &&... args) {
  ostringstream oss;
  oss << arg;
  dump_str_rec(oss, forward<U>(args)...);
  return oss.str();
}

// --------------- Fast I/O ------------------

void fastio() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  cout << fixed << setprecision(20);
}

// ------------------ ACL --------------------

// #include <atcoder/modint>
// constexpr int MOD = 998244353;
// constexpr int MOD = 1000000007;
// using mint = atcoder::static_modint<MOD>;
// ostream &operator<<(ostream &os, const mint &v) {
//   return os << v.val();
// }

// ------------ End of template --------------

#define endl "\n"
using ll = long long;
using pii = pair<int, int>;

const bool multitest = false;

template <class T>
struct BIT {
  int N;
  vector<T> bit;
  BIT(int N) : N(N) { bit = vector<T>(N + 1, T(0)); }
  void add(int i, T x) {
    i++;
    while (i <= N) {
      bit[i] += x;
      i += i & -i;
    }
    return;
  }
  T sum(int i) {
    i++;
    T res = T(0);
    while (i > 0) {
      res += bit[i];
      i -= i & -i;
    }
    return res;
  }
  T sum(int l, int r) { // [l,r]
    assert(l <= r);
    if (l == 0)
      return sum(r);
    else
      return sum(r) - sum(l - 1);
  }
};

bool solve() {
  ll W;
  int N;
  cin >> W >> N;
  if (W == 0 && N == 0) return false;
  vector<ll> x(N);
  cin >> x;

  vector<ll> y(N + 1);
  for (int i = 0; i < N; i++) y[i + 1] = y[i] + x[i];

  auto range = [&](ll a, ll b, int id, ll K) {
    int L, R;
    {
      int l = -1, r = id;
      while (r - l > 1) {
        int mid = (l + r) / 2;
        if (y[mid] + mid >= a)
          r = mid;
        else
          l = mid;
      }
      L = r;
    }
    {
      if (y[0] > b) return make_pair(1, 0);
      int l = 0, r = id;
      while (r - l > 1) {
        int mid = (l + r) / 2;
        if (y[mid] + K * mid <= b)
          l = mid;
        else
          r = mid;
      }
      R = l;
    }
    return make_pair(L, R);
  };

  auto check = [&](ll K) {
    BIT<int> bit(N + 1);
    bit.add(0, 1);
    for (int i = 1; i <= N; i++) {
      ll a = i - 1 + y[i] - W;
      ll b = K * (i - 1) + y[i] - W;
      auto [l, r] = range(a, b, i, K);
      if (l > r) continue;
      if (bit.sum(l, r) > 0) bit.add(i, 1);
    }
    for (int i = 0; i <= N; i++) {
      if (bit.sum(i, i) == 0) continue;
      if (y[N] - y[i] + (N - i - 1) * K <= W) return true;
    }
    return false;
  };

  ll l = 0, r = W;
  while (r - l > 1) {
    ll mid = (l + r) / 2ll;
    if (check(mid))
      r = mid;
    else
      l = mid;
  }
  cout << r << endl;
  return true;
}

int main() {
  fastio();
  if (!multitest) {
    while (solve()) {}
  } else {
    cerr << "[Warning] Multi testcase mode on" << endl;
    int t;
    cin >> t;
    while (t--) solve();
  }
  return 0;
}
accuracy: 1
time_ms: 6070
memory_kb: 4192
final_rank: 17

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

int main() {
    ll W, N;
    while (cin >> W >> N, W) {
        W++;
        vector<ll> X(N);
        for (auto&& x : X) {
            cin >> x;
            x++;
        }
        vector<ll> acc(N + 1);
        for (int i = 0; i < N; i++) {
            acc[i + 1] = acc[i] + X[i];
        }

        vector<ll> accwithspace(N + 1);
        vector<int> imos(N + 1);
        auto check = [&](ll maxspace) {
            accwithspace[0] = 0;
            for (int i = 0; i < N; i++) {
                accwithspace[i + 1] = accwithspace[i] + X[i] + maxspace;
            }
            imos[0] = 0;
            for (int i = 0; i < N; i++) {
                bool canbefront = false;
                if (i == 0)
                    canbefront = true;
                else if (i == 1)
                    canbefront = false;
                else {
                    int l, r;
                    l = lower_bound(cbegin(acc), cend(acc), acc[i] - W) - acc.begin();
                    r = lower_bound(cbegin(accwithspace), cend(accwithspace), accwithspace[i] - maxspace - W + 1) - accwithspace.begin();
                    canbefront = imos[r] - imos[l];
                }
                imos[i + 1] = imos[i] + canbefront;
                if (canbefront && ((acc.back() - acc[i]) <= W))
                    return true;
            }
            return false;
        };

        int ok = W;
        int ng = -1;
        while (abs(ok - ng) > 1) {
            int mid = (ok + ng) / 2;
            if (check(mid)) {
                ok = mid;
            } else {
                ng = mid;
            }
        }

        cout << ok + 1 << endl;
    }
}
accuracy: 1
time_ms: 3490
memory_kb: 4328
final_rank: 13

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

int main() {
    ll W, N;
    while (cin >> W >> N, W) {
        W++;
        vector<ll> X(N);
        for (auto&& x : X) {
            cin >> x;
            x++;
        }
        vector<ll> acc(N + 1);
        for (int i = 0; i < N; i++) {
            acc[i + 1] = acc[i] + X[i];
        }

        auto check = [&](ll maxspace) {
            vector<ll> accwithspace(N + 1);
            for (int i = 0; i < N; i++) {
                accwithspace[i + 1] = accwithspace[i] + X[i] + maxspace;
            }
            vector<int> imos(N + 1);
            for (int i = 0; i < N; i++) {
                bool canbefront = false;
                if (i == 0)
                    canbefront = true;
                else if (i == 1)
                    canbefront = false;
                else {
                    int l, r;
                    l = lower_bound(cbegin(acc), cend(acc), acc[i] - W) - acc.begin();
                    r = lower_bound(cbegin(accwithspace), cend(accwithspace), accwithspace[i] - maxspace - W + 1) - accwithspace.begin();
                    canbefront = imos[r] - imos[l];
                }
                imos[i + 1] = imos[i] + canbefront;
                if (canbefront && ((acc.back() - acc[i]) <= W))
                    return true;
            }
            return false;
        };

        int ok = W;
        int ng = -1;
        while (abs(ok - ng) > 1) {
            int mid = (ok + ng) / 2;
            if (check(mid)) {
                ok = mid;
            } else {
                ng = mid;
            }
        }

        cout << ok + 1 << endl;
    }
}
accuracy: 1
time_ms: 3490
memory_kb: 4540
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
int main(){
  while (true){
    int W, N;
    cin >> W >> N;
    if (W == 0 && N == 0){
      break;
    }
    vector<int> x(N);
    for (int i = 0; i < N; i++){
      cin >> x[i];
    }
    vector<int> S(N + 1);
    S[0] = 0;
    for (int i = 0; i < N; i++){
      S[i + 1] = S[i] + x[i];
    }
    int tv = W - 2, fv = 0;
    while (tv - fv > 1){
    	int mid = (tv + fv) / 2;
      vector<bool> dp(N + 1, false);
      dp[0] = true;
      vector<int> dpS(N + 2, 0);
      dpS[1] = 1;
      for (int i = 0; i < N; i++){
        int tv1 = i, fv1 = -1;
        while (tv1 - fv1 > 1){
          int mid1 = (tv1 + fv1) / 2;
          if (S[i + 1] - S[mid1] + (i - mid1) <= W){
            tv1 = mid1;
          } else {
            fv1 = mid1;
          }
        }
        int tv2 = tv1 - 1, fv2 = i;
        while (fv2 - tv2 > 1){
          int mid2 = (tv2 + fv2) / 2;
          int r = W - (S[i + 1] - S[mid2]);
          if (r <= mid * (i - mid2)){
            tv2 = mid2;
          } else {
            fv2 = mid2;
          }
        }
        if (dpS[tv2 + 1] - dpS[tv1] > 0){
          dp[i + 1] = true;
        }
        dpS[i + 2] = dpS[i + 1];
        if (dp[i + 1]){
          dpS[i + 2]++;
        }
      }
      bool ok = false;
      for (int i = 0; i <= N; i++){
        if (dp[i] && S[N] - S[i] + (N - i - 1) <= W){
          ok = true;
        }
      }
      if (ok){
        tv = mid;
      } else {
        fv = mid;
      }
    }
    cout << tv << endl;
  }
}
accuracy: 1
time_ms: 6250
memory_kb: 3456
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=998244353,MAX=80005,INF=1<<30;
ll dp[MAX];

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    while(1){
        ll W,N;cin>>W>>N;
        if(W==0) break;
        vector<ll> A(N+1),rui(N+2);
        for(int i=0;i<N;i++){
            cin>>A[i+1];
            rui[i+1]=rui[i]+A[i+1];
        }
        rui[N+1]=1LL<<60;
        
        ll left=0,right=W;
        while(right-left>1){
            ll mid=(left+right)/2;
            memset(dp,0,sizeof(dp));
            dp[0]=1;
            dp[1]=-1;
            
            for(int i=0;i<=N;i++){
                if(i) dp[i]+=dp[i-1];
                if(dp[i]==0) continue;
                if(i==N) break;
                
                if(rui[N]-rui[i]+N-i-1<=W){
                    dp[N]=1;
                    break;
                }
                int l=i+2,r=N+1;
                while(r-l>1){
                    int m=(l+r)/2;
                    if(rui[m]-rui[i]+m-i-1<=W) l=m;
                    else r=m;
                }
                
                int l2=i+1,r2=N+1;
                while(r2-l2>1){
                    int m2=(l2+r2)/2;
                    if(rui[m2]-rui[i]+mid*(m2-i-1)>=W) r2=m2;
                    else l2=m2;
                }
                
                if(r2<=l){
                    dp[r2]++;
                    dp[l+1]--;
                }
            }
            
            if(dp[N]) right=mid;
            else left=mid;
        }
        cout<<right<<endl;
    }
}
accuracy: 1
time_ms: 3890
memory_kb: 4408
final_rank: 16

code_snippet: #include <iostream>
#include <numeric>
#include <vector>

using namespace std;
using lint = long long;

bool solve() {
    lint w;
    int n;
    cin >> w >> n;
    if (w == 0) return false;

    vector<lint> xs(n);
    for (auto& x : xs) cin >> x;
    xs.insert(xs.begin(), 0);
    partial_sum(xs.begin(), xs.end(), xs.begin());

    lint ok = w, ng = 0;
    while (ok - ng > 1) {
        lint mid = (ok + ng) / 2;
        vector<int> nxt(n + 1, n);

        for (int l = n - 1; l >= 0; --l) {
            nxt[l] = nxt[l + 1];

            if ((xs[n] - xs[l]) + (n - l - 1) <= w) {
                nxt[l] = l;
                continue;
            }

            int rng = l, rok = n + 1;
            while (rok - rng > 1) {
                int r = (rok + rng) / 2;

                if ((xs[r] - xs[l]) + (r - l - 1) * mid >= w) {
                    rok = r;
                } else {
                    rng = r;
                }
            }

            int r = nxt[rok];
            if ((xs[r] - xs[l]) + (r - l - 1) <= w) nxt[l] = l;
        }

        if (nxt[0] == 0) {
            ok = mid;
        } else {
            ng = mid;
        }
    }

    cout << ok << "\n";
    return true;
}

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

    while (solve()) {}

    return 0;
}
accuracy: 1
time_ms: 2660
memory_kb: 4188
final_rank: 8

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

using namespace std;

#define REP(i, n) for (int i=0; i<(n); ++i)
#define RREP(i, n) for (int i=(int)(n)-1; i>=0; --i)
#define FOR(i, a, n) for (int i=(a); i<(n); ++i)
#define RFOR(i, a, n) for (int i=(int)(n)-1; i>=(a); --i)

#define SZ(x) ((int)(x).size())
#define ALL(x) (x).begin(),(x).end()

#define DUMP(x) cerr<<#x<<" = "<<(x)<<endl
#define DEBUG(x) cerr<<#x<<" = "<<(x)<<" (L"<<__LINE__<<")"<<endl;

template<class T>
ostream &operator<<(ostream &os, const vector <T> &v) {
    os << "[";
    REP(i, SZ(v)) {
        if (i) os << ", ";
        os << v[i];
    }
    return os << "]";
}

template<class T, class U>
ostream &operator<<(ostream &os, const pair <T, U> &p) {
    return os << "(" << p.first << " " << p.second << ")";
}

template<class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;

const ll MOD = 1e9 + 7;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
const ld eps = 1e-9;


template<int m>
struct mint {
    int x;

    mint(int x = 0) : x(((x % m) + m) % m) {}

    mint operator-() { return x ? m - x : 0; }

    mint &operator+=(mint r) {
        if ((x += r.x) >= m) x -= m;
        return *this;
    }

    mint &operator-=(mint r) {
        if ((x -= r.x) < 0) x += m;
        return *this;
    }

    mint &operator*=(mint r) {
        x = ((ll) x * r.x) % m;
        return *this;
    }

    mint inv() {
        int a = x, b = m, u = 1, v = 0, t;
        while (b > 0) {
            t = a / b;
            swap(a -= t * b, b);
            swap(u -= t * v, v);
        }
        return u;
    }

    mint &operator/=(mint r) { return *this *= r.inv(); }

    friend mint operator+(mint l, mint r) { return l += r; }

    friend mint operator-(mint l, mint r) { return l -= r; }

    friend mint operator*(mint l, mint r) { return l *= r; }

    friend mint operator/(mint l, mint r) { return l /= r; }

    mint pow(ll n) {
        mint ret = 1, tmp = *this;
        while (n) {
            if (n & 1) ret *= tmp;
            tmp *= tmp, n >>= 1;
        }
        return ret;
    }

    friend bool operator==(mint l, mint r) { return l.x == r.x; }

    friend bool operator!=(mint l, mint r) { return l.x != r.x; }

    friend ostream &operator<<(ostream &os, mint a) {
        return os << a.x;
    }

    friend istream &operator>>(istream &is, mint &a) {
        int x;
        is >> x;
        a = x;
        return is;
    }
};


template<typename T>
struct Combination {
    int _n = 1;
    vector<T> _fact{1}, _rfact{1};

    void extend(int n) {
        if (n <= _n) return;
        _fact.resize(n);
        _rfact.resize(n);
        for (int i = _n; i < n; ++i) _fact[i] = _fact[i - 1] * i;
        _rfact[n - 1] = 1 / _fact[n - 1];
        for (int i = n - 1; i > _n; --i) _rfact[i - 1] = _rfact[i] * i;
        _n = n;
    }

    T fact(int k) {
        extend(k + 1);
        return _fact.at(k);
    }

    T rfact(int k) {
        extend(k + 1);
        return _rfact.at(k);
    }

    T P(int n, int r) {
        if (r < 0 or n < r) return 0;
        return fact(n) * rfact(n - r);
    }

    T C(int n, int r) {
        if (r < 0 or n < r) return 0;
        return fact(n) * rfact(r) * rfact(n - r);
    }

    T H(int n, int r) {
        return (n == 0 and r == 0) ? 1 : C(n + r - 1, r);
    }
};



bool solve() {
    int w, n; cin >> w >> n;
    if (w == 0 and n == 0) return false;
    vi x(n); REP(i, n) cin >> x[i];

    vi xs(n+1);
    REP(i, n) xs[i+1] = xs[i] + x[i];

    vi dp1(n);
    {
        int r = 0, sum = 0;
        REP(l, n) {
            while (r < n and sum + x[r] + (r - l) <= w) sum += x[r++];
            dp1[l] = r;
            sum -= x[l];
        }
    }
    //DUMP(dp1);

    auto check = [&](int s) {
        // 隙間最大s で可能か?
        vi dp2(n, n);
        {
            int r = 0, sum = 0;
            REP(l, n) {
                while (r < n and sum + x[r] + (r - l) * s < w) sum += x[r++];
                if (r < n) dp2[l] = r;
                sum -= x[l];
            }
        }
        //DUMP(dp2);

        //{
        //    vi dp(n + 1);
        //    dp[0] = 1;
        //    REP(i, n) {
        //        if (dp[i] == 0) continue;
        //        for (int j = dp2[i]; j < dp1[i]; ++j) {
        //            dp[j + 1] = 1;
        //        }
        //    }
        //    DUMP(dp);
        //}

        //{
            vi dp(n+1);
            vi dps(n+2);
            dps[0] = 1, dps[1] = -1;
            dp[0] = 1;
            REP(i, n) {
                if (dp[i] == 0) {
                    dp[i+1] = dp[i] + dps[i+1];
                    continue;
                }
                //for (int j = dp2[i]; j < dp1[i]; ++j) {
                //    dp[j+1] = 1;
                //}
                if (dp2[i] < dp1[i]) {
                    ++dps[dp2[i] + 1];
                    --dps[dp1[i] + 1];
                }
                dp[i+1] = dp[i] + dps[i+1];
            }
            //DUMP(dp);
            //DUMP(dps);
        //}

        for (int i = n; i >= 0; --i) {
            if (dp[i] > 0) {
                int sum = xs[n] - xs[i];
                int cnt = n - i;
                return sum + cnt - 1 <= w;
            }
        }
        return false;
    };
    //while (true) {
    //    int y; cin >> y;
    //    check(y);
    //}

    int ok = w, ng = 0;
    while (abs(ok - ng) > 1) {
        int mid = (ok + ng) / 2;
        (check(mid) ? ok : ng) = mid;
    }
    cout << ok << endl;

    return true;
}

int main() {
    //ifstream in("in.txt");
    //cin.rdbuf(in.rdbuf());
    while (solve()) {}
    return 0;
}
accuracy: 1
time_ms: 930
memory_kb: 4144
final_rank: 6

code_snippet: #include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<cmath>
#include<algorithm>
#include<map>
#include<queue>
#include<deque>
#include<iomanip>
#include<tuple>
#include<cassert>
#include<set>
using namespace std;
typedef long long int LL;
typedef pair<int,int> P;
typedef pair<LL,int> LP;
const int INF=1<<30;
const LL MAX=1e9+7;

void array_show(int *array,int array_n,char middle=' '){
	for(int i=0;i<array_n;i++)printf("%d%c",array[i],(i!=array_n-1?middle:'\n'));
}
void array_show(LL *array,int array_n,char middle=' '){
	for(int i=0;i<array_n;i++)printf("%lld%c",array[i],(i!=array_n-1?middle:'\n'));
}
void array_show(vector<int> &vec_s,int vec_n=-1,char middle=' '){
	if(vec_n==-1)vec_n=vec_s.size();
	for(int i=0;i<vec_n;i++)printf("%d%c",vec_s[i],(i!=vec_n-1?middle:'\n'));
}
void array_show(vector<LL> &vec_s,int vec_n=-1,char middle=' '){
	if(vec_n==-1)vec_n=vec_s.size();
	for(int i=0;i<vec_n;i++)printf("%lld%c",vec_s[i],(i!=vec_n-1?middle:'\n'));
}

int n,m;
vector<LL> va,vs1,vs2;
int t[550000];

bool check(int space){
	int i,j,k;
	LL a,b,c;
	int x,y;
	vs2.assign(n+1,0);
	for(i=0;i<n;i++){
		vs2[i+1]=vs2[i]+va[i]+space;
	}
	memset(t,0,sizeof(t));
	a=1,t[1]=-1;
	for(i=0;i<n;i++){
		a+=t[i];
		if(a==0)continue;
		int z[3]={i,n+1};
		while(z[1]-z[0]>1){
			z[2]=(z[0]+z[1])/2;
			b=vs1[z[2]]-vs1[i];
			if(b>m+1)z[1]=z[2];
			else z[0]=z[2];
		}
		x=z[1];
		z[0]=i,z[1]=n+1;
		while(z[1]-z[0]>1){
			z[2]=(z[0]+z[1])/2;
			b=vs2[z[2]]-vs2[i];
			if(b>=m+space)z[1]=z[2];
			else z[0]=z[2];
		}
		y=z[1];
		if(x>n)return true;
		if(y<x)t[y]++,t[x]--;
	}
	return false;
}

int main(){
	int i,j,k;
	int a,b,c;
	while(cin>>m>>n){
		if(m==0 && n==0)break;
		va.clear();
		vs1.assign(n+1,0);
		for(i=0;i<n;i++){
			cin>>a;
			va.push_back(a);
			vs1[i+1]=vs1[i]+va[i]+1;
		}
		int z[3]={0,m};
		while(z[1]-z[0]>1){
			z[2]=(z[0]+z[1])/2;
			if(check(z[2]))z[1]=z[2];
			else z[0]=z[2];
		}
		cout<<z[1]<<endl;
	}
}
accuracy: 1
time_ms: 5040
memory_kb: 6136
final_rank: 19

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

const int INF = 80010;

int w,n,a[50010],s[50010],dp[50010];

bool check(int x){
	dp[1] = 1;
	int l = 0,r = 0;
	for(int i = 1;i <= n;i++){
		while(i > l && s[i] - s[l] + (i - l - 1) > w) l++;
		while(i > r && s[i] - s[r] + (i - r - 1) * x >= w) r++;
		dp[i + 1] = dp[i] + !!(dp[r] - dp[l]);
	}
	l = n;
	while(l >= 0 && s[n] - s[l] + n - l - 1 < w) l--;
	return dp[n + 1] - dp[l + 1];
}

void solve(){
	for(int i = 0;i < n;i++){
		scanf("%lld",&a[i]);
		s[i + 1] = s[i] + a[i];
	}
	int ng = 0,ok = INF;
	while(ok - ng > 1){
		int mid = (ok + ng) / 2;
		if(check(mid)) ok = mid;
		else ng = mid;
	}
	printf("%lld\n",ok);
}

signed main(){
	while(cin >> w >> n,n) solve();
}
accuracy: 1
time_ms: 730
memory_kb: 4356
final_rank: 7