1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <bits/stdc++.h>
using namespace std;
#define fwd(i, a, n) for (int i = (a); i < (n); i++)
#define rep(i, n) fwd(i, 0, n)
#define all(X) X.begin(), X.end()
#define sz(X) int(size(X))
#define pb push_back
#define eb emplace_back
#define st first
#define nd second
using pii = pair<int, int>; using vi = vector<int>;
using ll = long long; using ld = long double;
#ifdef LOC
auto SS = signal(6, [](int) { *(int *)0 = 0; });
#define DTP(x, y) auto operator << (auto &o, auto a) -> decltype(y, o) { o << "("; x; return o << ")"; }
DTP(o << a.st << ", " << a.nd, a.nd);
DTP(for (auto i : a) o << i << ", ", all(a));
void dump(auto... x) { (( cerr << x << ", " ), ...) <<
'\n'; }
#define deb(x...) cerr << setw(4) << __LINE__ << ":[" #x "]: ", dump(x)
#else
#define deb(...) 0
#endif
 
const int K = 1000;

array<ll, K+1> two;
array<ll, K+1> three;

void solve(){
    int n; cin >> n;
    vector<int> a(n+1);
    vector<int> pref(n+2, 0);
    vector<int> suf(n+2, 0);
    fwd(i, 1, n+1)cin >> a[i];
    int res = 0;
    fwd(i, 1, n+1){
        pref[i] = pref[i-1];
        if(a[i]){
            res++;
            pref[i]++;
        }
    }
    for(int i = n; i >= 0; i--){
        suf[i] = suf[i+1];
        if(a[i])suf[i]++;
    }
    array<int, K+1> current;
    array<int, K+1> nxt;
    for(int i = 0; i <= K; i++)current[i] = nxt[i] = 0;
    for(int i = 1; i <= n; i++){
        ll b = 0;
        for(int x = K; x >= 0; x--){
            ll c = suf[i+1] + x;
            ll a1;
            if(b > 0){
                a1 = pref[i-1] + current[min<ll>(K, x + b - 1)];
                while(b > 0 && three[b] + two[b] * (a1 + c) + a1 * b * c >= a[i]){
                    b--;
                    a1 = pref[i-1] + current[min<ll>(K, x + b - 1)];
                }
            }
            a1 = pref[i-1] + current[min<ll>(K, x + b)];
            while(three[b+1] + two[b+1] * (a1 + c) + a1 * (b+1) * c < a[i]){
                b++;
                a1 = pref[i-1] + current[min<ll>(K, x + b)];
            }
            nxt[x] = (int)(current[min<ll>(K, x + b)] + b);
        }
        current = nxt;
        // deb(i, current);
    }
    cout << (current[0] + res) << "\n";
}

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout << fixed << setprecision(10); 
    int t; cin >> t;
    for(ll i = 0; i <= K; i++){
        two[i] = (i * (i-1)) / 2;
        three[i] = (i * (i-1) * (i-2)) / 6;
    }
    while(t--){
        solve();
    }
    return 0;
}