COFO::1462D Add to Neighbour and Remove

Problem

Point

Design

Complexity

Code

#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<math.h>
#include<algorithm>
#define rep(i,a,b) for(LL i=(a);i<(b);i++)
#define r_rep(i,a,b) for(LL i=(a);i>(b);i--)
typedef long long int LL;
using namespace std;

LL n;
LL a[3010];
LL SUM[3010][3010];
LL mn;
LL findRange(LL v, LL id, LL cnt){
    if(mn < cnt) return n-1;
    if(id == n) return cnt;
    LL bst = n;
    rep(i, id, n){
        if(SUM[id][i] == v){
            LL ret = findRange(v, i+1, cnt + (i - id));
            if(ret < bst) bst = ret;
        }else if(SUM[id][i] > v) break;
    }
    mn = min(mn, bst);
    return bst;
}
LL solve(){
    //rep(i, 0, 3010) rep(j, 0, 3010) SUM[i][j] = 0;
    
    cin >> n;
    rep(i, 0, n) cin >> a[i];
    bool f = true;
    rep(i, 0, n-1){
        if(a[i] != a[i+1]){ f = false; break;}
    }
    if(f){
        return 0;
    }
    
    rep(st, 0, n){
        SUM[st][st] = a[st];
        rep(en, st+1, n){
            SUM[st][en] = SUM[st][en-1] + a[en];
        }
    }
    
    
    mn = n-1;
    LL bst = n-1;
    rep(i, 0, n-1){
        LL ret = findRange(SUM[0][i], i+1, i);
        if(bst > ret) bst = ret;
    }
    return bst;
}
int main(){
    cin.tie(nullptr);
    cout.tie(nullptr);
 //   freopen("input.txt", "r", stdin);
    int tc; cin >> tc;
    while(tc--)
        cout << solve() << '\n';
}