Problem:
Tow Polygons
Yae decided to make a polygon by connecting three or more straight sticks and give it to her boyfriend, Jo. The sticks can only be connected at their end points. All end points must be on the same plane. Only two sticks can be connected at a single junction point, and the angle between them can be determined freely.
Yae is trying to make two polygons of equal size using all the sticks she has.
Using all the given sticks, make two polygons such that the absolute value of the difference between the lengths of their perimeters is minimized. Given the length of each stick, write a program to find the absolute value of the difference in the lengths of the perimeters of the two polygons. If you cannot create two polygons, report it.

For $m$ ($ \leq 3$) sticks of length $a_1 \leq a_2 \leq  ... \leq a_m$, if $a_m ＜a_1+a_2+ ... +a_{m-1}$, we can create a polygon with these $m$ sticks.
Input
The input is given in the following form.
$N$ 
$a_1$ $a_2$ ... $a_N$
The first line gives the number of sticks $N$ ($6 \leq N \leq 40$). The second line gives the length of each stick $a_i$ ($1 \leq a_i \leq 100$).
Output
If two polygons can be constructed using all the given sticks, output the minimum absolute value of the difference in length in a line. If two polygons cannot be constructed, output "-1" in a line.
Sample Input and Output
Sample Input 1
6
2 2 3 2 2 2
Sample Output 1
1
Sample Input 2
7
2 2 3 2 2 2 1
Sample Output 2
0
Sample Input 3
6
1 1 1 1 2 4
Sample Output 3
-1

Submitted solutions:

code_snippet: //#pragma GCC target ("avx2")
//#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define _USE_MATH_DEFINES
#include<iostream>
#include<string>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<list>
#include<iomanip>
#include<vector>
#include<random>
#include<functional>
#include<algorithm>
#include<stack>
#include<cstdio>
#include<cstring>
#include<bitset>
#include<unordered_map>
#include<climits>
#include<fstream>
#include<complex>
#include<time.h>
#include<cassert>
#include<functional>
#include<numeric>
#include<tuple>
using namespace std;
using ll = long long;
using ld = long double;
using H = pair<ll, ll>;
using P = pair<ll, H>;
using vi = vector<ll>;
#define all(a) (a).begin(),(a).end()
#define fs first
#define sc second
#define xx first
#define yy second.first
#define zz second.second
#define Q(i,j,k) mkp((i),mkp((j),(k)))
#define rng(i,s,n) for(ll 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 ssp(i,n) (i==(ll)(n)-1?"\n":" ")
#define ctoi(c) (int)((c)-'0')
#define itoc(c) (char)((c)+'0')
#define cyes printf("Yes\n")
#define cno printf("No\n")
#define cdf(n) for(int quetimes_=(n);quetimes_>0;quetimes_--)
#define gcj printf("Case #%lld: ",quetimes_+1)
#define readv(a,n) (a).resize((n),0);rep(i,(n)) (a)[i]=read()
#define found(a,x) (a.find(x)!=a.end())
constexpr ll mod = (ll)1e9 + 7;
constexpr ll Mod = 998244353;
constexpr ld EPS = 1e-10;
constexpr ll inf = (ll)3 * 1e18;
constexpr int Inf = (ll)15 * 1e8;
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; }
ll read() { ll u, k = scanf("%lld", &u); return u; }
string reads() { string s; cin >> s; return s; }
H readh(short g = 0) { H u; int k = scanf("%lld %lld", &u.fs, &u.sc); if (g == 1) u.fs--, u.sc--; if (g == 2) u.fs--; return u; }
bool ina(H t, int h, int w) { return 0 <= t.fs && t.fs < h && 0 <= t.sc && t.sc < w; }
bool ina(int t, int l, int r) { return l <= t && t < r; }
ll gcd(ll i, ll j) { return j ? gcd(j, i % j) : i; }
ll ppc(ll x) {
    int sum = 0; for (int i = 0; i < 60; i++)if ((1ll << i) & x) sum++;
    return sum;
}
template<typename T>
void fin(T x) { cout << x << endl; exit(0); }

template<typename T>
class csum {
    vec<T> v;
public:
    csum(vec<T>& a) :v(a) { build(); }
    csum() {}
    csum(int sz) { init(sz); }
    void init(int sz) { v = vector<T>(sz + 1, 0); }
    void init(vec<T>& a) { v = a; build(); }
    void build() {
        for (int i = 1; i < v.size(); i++) v[i] += v[i - 1];
    }
    void add(int l, int r, T x) {
        v[l] += x;
        v[r] -= x;
    }//[l,r)
    void add(int t, T x) {
        v[t] += x;
    }//[l,r)
    //[l,r]
    T a(int l, int r) {
        if (r < l) return 0;
        return v[r] - (l == 0 ? 0 : v[l - 1]);
    }
    //[l,r)
    T b(int l, int r) {
        return a(l, r - 1);
    }
    T a(pair<int, int>t) {
        return a(t.first, t.second);
    }
    T b(pair<int, int>t) {
        return b(t.first, t.second);
    }
    T operator[](int x)const {
        return v[x];
    }
};
class via {
    using H = pair<ll, ll>;
    bool comp;
public:
    vector<H>a;
    via() :comp(true) {}
    via(vector<H>dat) :a(dat), comp(false) { build(); }
    void push(int l, int r) { a.push_back(H{ l,r }); comp = false; }
    void push(H a) { push(a.first, a.second); }
    void build() {
        if (comp) return;
        comp = true;
        sort(a.begin(), a.end());
        int fst = -1; ll lst = -1;
        vector<H>b;
        for (int i = 0; i < a.size(); i++) {
            if (fst < 0) fst = i, lst = a[i].second;
            if (lst < a[i].first) {
                b.push_back(H{ a[fst].first,lst });
                fst = i, lst = a[i].second;
            }
            else if (lst < a[i].second) lst = a[i].second;
        }
        if (~fst) b.push_back(H{ a[fst].first, lst });
        a = b;
    }
    ll size() { return ll(a.size()); }
    ll sum() {
        build();
        ll sum = 0;
        for (auto g : a) sum += g.second - g.first;
        return sum;
    }
    via inter(via& v) {
        build(); v.build();
        via ret;
        for (auto g : a) ret.push(g);
        for (auto g : v.a) ret.push(g);
        ret.build(); return ret;
    }
    via comb(via& v) {
        build(); v.build();
        int s = 0, t = 0;
        via ret;
        while (s < a.size() && t < v.size()) {
            if (v[t].second <= a[s].first)  t++;
            else if (a[s].second <= v[t].first) s++;
            else {
                ret.push(max(a[s].first, v[t].first), min(a[s].second, v[t].second));
                if (a[s].second <= v[t].second) s++;
                else t++;
            }
        }
        return ret;
    }
    H& operator[](int t) { return a[t]; }
};
template<ll mod>
class modint {
public:ll v;
      modint(ll v = 0) { s(v % mod + mod); }
      constexpr static int fn_ = (ll)2e6 + 5;
      static vector<modint>fact, comp;
      modint pow(ll x) const {
          modint b(v), c(1);
          while (x) {
              if (x & 1) c *= b;
              b *= b;
              x >>= 1;
          }
          return c;
      }
      inline modint& s(int vv) {
          v = vv < mod ? vv : vv - mod;
          return *this;
      }
      inline modint inv()const { return pow(mod - 2); }
      inline modint operator-()const { return modint() - *this; }
      inline modint& operator+=(const modint b) { return s(v + b.v); }
      inline modint& operator-=(const modint b) { return s(v + mod - b.v); }
      inline modint& operator*=(const modint b) { v = v * b.v % mod; return *this; }
      inline modint& operator/=(const modint b) { v = v * b.inv().v % mod; return *this; }
      inline modint operator+(const modint& b) const { return modint(v) += b; }
      inline modint operator-(const modint& b) const { return modint(v) -= b; }
      inline modint operator*(const modint& b) const { return modint(v) *= b; }
      inline modint operator/(const modint& b) const { return modint(v) /= b; }
      friend ostream& operator<<(ostream& os, const modint& m) {
          return os << m.v;
      }
      friend istream& operator>>(istream& is, modint& m) {
          int x; is >> x; m = modint(x);
          return is;
      }
      bool operator<(const modint& r)const { return v < r.v; }
      bool operator>(const modint& r)const { return v > r.v; }
      bool operator<=(const modint& r)const { return v <= r.v; }
      bool operator>=(const modint& r)const { return v >= r.v; }
      bool operator==(const modint& r)const { return v == r.v; }
      bool operator!=(const modint& r)const { return v != r.v; }
      explicit operator bool()const { return v; }
      explicit operator int()const { return v; }
      modint comb(modint k) {
          if (k > *this) return modint();
          if (fact.empty()) combinit();
          if (v >= fn_) {
              if (k > *this - k) k = *this - k;
              modint tmp(1);
              for (int i = v; i >= v - k.v + 1; i--) tmp *= modint(i);
              return tmp * comp[k.v];
          }
          return fact[v] * comp[k.v] * comp[v - k.v];
      }//nCk
      modint perm(modint k) {
          if (k > *this) return modint();
          if (fact.empty()) combinit();
          if (v >= fn_) {
              modint tmp(1);
              for (int i = v; i >= v - k.v + 1; i--) tmp *= modint(i);
              return tmp;
          }
          return fact[v] * comp[v - k.v];
      }//nPk
      static void combinit() {
          fact.assign(fn_, modint());
          fact[0] = 1;
          for (int i = 1; i < fn_; i++) fact[i] = fact[i - 1] * modint(i);
          comp.assign(fn_, modint());
          comp[fn_ - 1] = fact[fn_ - 1].inv();
          for (int i = fn_ - 2; i >= 0; i--) comp[i] = comp[i + 1] * modint(i + 1);
      }
};
using mint = modint<ll(1e9 + 7)>; template<>vec<mint> mint::fact = vec<mint>(); template<>vec<mint> mint::comp = vec<mint>();
//--------------------------------------------------------------
//--------------------------------------------------------------
int n;
short dp[2][42][42][4001][2];
signed main() {
    cin >> n;
    vi a; readv(a, n);
    vi b = a;
    rng(i, 1, n) b[i] += b[i - 1];
    rep(i, 1)rep(x, n + 1)rep(y, n + 1)rep(k, b[n - 1] + 1) {
        dp[0][x][y][k][0] = 41;
        dp[0][x][y][k][1] = -1;
    }


    dp[0][n][n][0][0] = 0;
    dp[0][n][n][0][1] = 0;
    rep(i, n){
        int nxt = (i + 1) & 1;
        rep(x, n + 1)rep(y, n + 1)rep(k, b[n - 1] + 1) {
            dp[nxt][x][y][k][0] = 41;
            dp[nxt][x][y][k][1] = -1;
        }
        rep(x, n + 1)rep(y, n + 1)rep(k, b[i] + 1) {

            if (dp[i & 1][x][y][k][1] < 0) continue;

            if (x == n) {
                chmin(dp[nxt][i][y][a[i]][0], short(dp[i & 1][x][y][k][0] + 1));
                chmax(dp[nxt][i][y][a[i]][1], short(dp[i & 1][x][y][k][1] + 1));
            }
            if (x < n) {
                if (a[i] > a[x]) {
                    chmin(dp[nxt][i][y][k + a[i]][0], short(dp[i & 1][x][y][k][0] + 1));
                    chmax(dp[nxt][i][y][k + a[i]][1], short(dp[i & 1][x][y][k][1] + 1));
                }
                else {
                    chmin(dp[nxt][x][y][k + a[i]][0], short(dp[i & 1][x][y][k][0] + 1));
                    chmax(dp[nxt][x][y][k + a[i]][1], short(dp[i & 1][x][y][k][1] + 1));
                }
            }

            if (y == n) {
                chmin(dp[nxt][x][i][k][0], short(dp[i & 1][x][y][k][0]));
                chmax(dp[nxt][x][i][k][1], short(dp[i & 1][x][y][k][1]));
            }
            if (y < n) {
                if (a[i] > a[y]) {
                    chmin(dp[nxt][x][i][k][0], short(dp[i & 1][x][y][k][0]));
                    chmax(dp[nxt][x][i][k][1], short(dp[i & 1][x][y][k][1]));
                }
                else {
                    chmin(dp[nxt][x][y][k][0], short(dp[i & 1][x][y][k][0]));
                    chmax(dp[nxt][x][y][k][1], short(dp[i & 1][x][y][k][1]));
                }
            }
        }
    }

    ll ans = inf;
    rep(i, n)rep(j, n)rep(k, b[n - 1] + 1) {
        if (dp[n & 1][i][j][k][1] > 0 &&
            k - a[i] > a[i] &&
            (b[n - 1] - k) - a[j] > a[j]) {

            if (dp[n & 1][i][j][k][1] < 3 || n - dp[n & 1][i][j][k][0] < 3) continue;
            chmin(ans, abs((b[n - 1] - k) - k));

        }
    }
    if (ans == inf) ans = -1;
    cout << ans << endl;
}
accuracy: 1
time_ms: 210
memory_kb: 57904
final_rank: 9

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

int main() {
  int n;
  std::cin >> n;

  std::vector< int > as(n);
  for (auto &a: as) std::cin >> a;

  std::sort(as.begin(), as.end());
  int sum_a = std::accumulate(as.begin(), as.end(), 0);

  int ans = sum_a;
  for (int m = 0; m < n - 1; m++) {
    auto dp = vector(n + 1, vector(sum_a + 1, 0));
    dp[0][0] = 1;

    for (int i = 0; i < m; i++) {
      auto ndp = dp;
      for (int j = 0; j < n; j++) {
        for (int sum = 0; sum <= sum_a; sum++) {
          if (not dp[j][sum]) continue;
          if (sum + as[i] > sum_a) continue;
          ndp[j + 1][sum + as[i]] = 1;
        }
      }
      dp = ndp;
    }

    for (int j = 2; j <= n; j++) {
      for (int sum = 0; sum <= sum_a; sum++) {
        if (not dp[j][sum]) continue;

        int s1 = sum + as[m];
        int s2 = sum_a - s1;
        int cnt1 = j + 1;
        int cnt2 = n - cnt1;
        if (2 * as[m] >= s1) continue;
        if (2 * as.back() >= s2) continue;
        if (cnt1 < 3) continue;
        if (cnt2 < 3) continue;
        ans = std::min(ans, std::abs(s1 - s2));
      }
    }
  }

  if (ans == sum_a) {
    std::cout << -1 << std::endl;
  } else {
    std::cout << ans << std::endl;
  }
}
accuracy: 1
time_ms: 180
memory_kb: 4280
final_rank: 7

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

using ll=long long;
#define rep(i,n) for(int i=0;i<int(n);i++)
#define rep2(i,s,n) for(int i=int(s);i<int(n);i++)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
const int big=1e9+7;
//const int big=998244353;
const char newl='\n';
const int inf=1e9+10;
const ll INF=ll(1e18)+10;
const int dx[]={1,0,-1,0};
const int dy[]={0,1,0,-1};

using P=pair<ll,int>;
priority_queue<P,vector<P>,greater<P>> q;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    
    int n;
    cin >> n;
    vector<int> a(n);
    rep(i,n)cin >> a[i];
    sort(all(a));
    int ans=inf;
    rep(M,n-1){
        int MM=n-1;
        vector<vector<pair<bool,int>>> dp(n+1,vector<pair<bool,int>>(40*100+1));
        dp[0][0]={true,0};
        rep(i,n)rep(j,40*100+1)if(dp[i][j].first){
            if(i<=M)dp[i+1][j+a[i]]={true,dp[i][j].second};
            if(i<=MM && i!=M)dp[i+1][j]={true,dp[i][j].second+a[i]};
        }

        rep(j,40*100+1)if(dp.back()[j].first){
            if(j-a[M]>a[M] && dp.back()[j].second-a[MM]>a[MM])
                ans=min(ans,abs(j-dp.back()[j].second));
        }
    }
    if(ans==(int)inf)ans=-1;
    cout << ans << newl;
}
accuracy: 1
time_ms: 10
memory_kb: 4420
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long mod1 = 1000000007;
const long long mod2 = 998244353;
double pi = 3.141592653589;
using ll = long long;
vector<ll> dx = {-1,0,1,0,1,1,-1,-1};
vector<ll> dy = {0,1,0,-1,1,-1,1,-1};
vector<char> abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<char> ABC = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 
struct UnionFind{
    vector<ll> par, siz;
    
    UnionFind(ll n):par(n,-1),siz(n,1){}
    
    ll root(ll x){//親を返す
        if(par[x] == -1) return x;
        else return par[x] = root(par[x]);
    }
    
    bool issame(ll x,ll y){//同じグループかどうか
        return root(x) == root(y);
    }
    
    bool unite(ll x, ll y){//合体
        x = root(x); y = root(y);
        if(x == y) return false;
        if(siz[x] < siz[y]) swap(x,y);
        par[y] = x;
        siz[x] += siz[y];
        return true;
    }
    
    ll size(ll x){//xがいるグループのサイズ
        return siz[root(x)];
    }
    
    
    
};
 
long long pow2(long long x,long long n){
    long long ans = 1;
    while(n != 0){
        long long a = x;
        long long z = 1;
        while(z*2 <= n){
            a *=a;
            a=a%mod2;
            z*=2;
        }
        ans*=a;
        ans=ans%mod2;
        n-=z;
    }
    return ans; 
}//累乗 x^n
 
template<typename T>
void input_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        cin >> A.at(i);
    }
    return;
}//入力を配列で受け取る
 
template<typename T>
void output_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        if(i != 0){
            cout << " ";
        }
        cout << A.at(i);
    }
    cout << endl;
    return;
}//配列を出力
 
template<typename T>
long long count_x(vector<T> &A,T x){
    long long counter = 0;
    for(int i = 0; i < (int)A.size(); i++){
        if(A.at(i) == x){
            counter++;
        }
    }
    return counter;
}//配列内のxの個数をreturn
 
template<typename T>
long long duplicate(vector<T> &A){
    ll ans = 0;
    ll N = A.size();
    T a = A.at(0);
    for(int i = 1; i < N; i++){
        if(a == A.at(i)) ans++;
        else a = A.at(i);
    }
    return ans;
}
 
template<typename T>
void chmin(T &a,T b){
    if(a>b){
        a = b;
    }
    return;
}
 
template<typename T>
void chmax(T&a,T b){
    if(a < b){
        a = b;
    }
    return;
}
 
/*
絶対値   abs()
配列の要素の追加   push_back() 
char→intに変換   -'0'
string→intに変換   atoi(文字列名.c_str())
配列の中身をN個の０で初期化   配列名.resize(N)
配列の中身をN個のaで初期化   配列名.assign(N,a)
配列の中からK以上の数字の最小値を出力　lower_bound(配列.begin(),配列.end(),K)
*/
int main(){
    ll N; cin >> N;
    vector<ll> v(N);
    input_vec(v);
    sort(v.begin(),v.end());
    ll su = 0;
    for(int i = 0; i < N; i++){
        su+=v[i];
    }
    vector<vector<pair<ll,ll>>> can(N+1);
    can[0].push_back(make_pair(0,0));
    for(int i = 0; i < N; i++){
        set<ll> check;
        //cout << "o" << endl;
        for(auto a: can[i]){
            //cout << check.size() << endl;
            ll b,c; tie(b,c) = a;
            //cout << b << " ";
            if(!check.count(b))can[i+1].push_back(make_pair(b,c));
            if(!check.count(b+v[i]))can[i+1].push_back(make_pair(b+v[i],c+1));
            check.insert(b);
            check.insert(b+v[i]);
        }
        //cout << endl;
        sort(can[i].begin(),can[i].end());
        
    }
    
    
    ll ans = mod1;
    for(int i = 0; i < N-1; i++){
        ll mx = v[N-1],my = v[i];
        for(auto z: can[i]){
            ll a,x; tie(a,x) = z;
            a+=my;
            ll b = su-a;
            x++;
            ll y = N-x;
            //printf("%lld %lld %lld %lld %lld %lld\n",b,mx,a,my,x,y);
            if(my>=a-my||mx>=b-mx)continue;
            if(x<3||y<3) continue;
            ans = min(ans,abs(a-b));
        }
    }
    if(ans == mod1) cout << -1 << endl;
    else cout << ans << endl;
    
}
accuracy: 1
time_ms: 10
memory_kb: 3988
final_rank: 1

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long mod1 = 1000000007;
const long long mod2 = 998244353;
double pi = 3.141592653589;
using ll = long long;
vector<ll> dx = {-1,0,1,0,1,1,-1,-1};
vector<ll> dy = {0,1,0,-1,1,-1,1,-1};
vector<char> abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<char> ABC = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 
struct UnionFind{
    vector<ll> par, siz;
    
    UnionFind(ll n):par(n,-1),siz(n,1){}
    
    ll root(ll x){//親を返す
        if(par[x] == -1) return x;
        else return par[x] = root(par[x]);
    }
    
    bool issame(ll x,ll y){//同じグループかどうか
        return root(x) == root(y);
    }
    
    bool unite(ll x, ll y){//合体
        x = root(x); y = root(y);
        if(x == y) return false;
        if(siz[x] < siz[y]) swap(x,y);
        par[y] = x;
        siz[x] += siz[y];
        return true;
    }
    
    ll size(ll x){//xがいるグループのサイズ
        return siz[root(x)];
    }
    
    
    
};
 
long long pow2(long long x,long long n){
    long long ans = 1;
    while(n != 0){
        long long a = x;
        long long z = 1;
        while(z*2 <= n){
            a *=a;
            a=a%mod2;
            z*=2;
        }
        ans*=a;
        ans=ans%mod2;
        n-=z;
    }
    return ans; 
}//累乗 x^n
 
template<typename T>
void input_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        cin >> A.at(i);
    }
    return;
}//入力を配列で受け取る
 
template<typename T>
void output_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        if(i != 0){
            cout << " ";
        }
        cout << A.at(i);
    }
    cout << endl;
    return;
}//配列を出力
 
template<typename T>
long long count_x(vector<T> &A,T x){
    long long counter = 0;
    for(int i = 0; i < (int)A.size(); i++){
        if(A.at(i) == x){
            counter++;
        }
    }
    return counter;
}//配列内のxの個数をreturn
 
template<typename T>
long long duplicate(vector<T> &A){
    ll ans = 0;
    ll N = A.size();
    T a = A.at(0);
    for(int i = 1; i < N; i++){
        if(a == A.at(i)) ans++;
        else a = A.at(i);
    }
    return ans;
}
 
template<typename T>
void chmin(T &a,T b){
    if(a>b){
        a = b;
    }
    return;
}
 
template<typename T>
void chmax(T&a,T b){
    if(a < b){
        a = b;
    }
    return;
}
 
/*
絶対値   abs()
配列の要素の追加   push_back() 
char→intに変換   -'0'
string→intに変換   atoi(文字列名.c_str())
配列の中身をN個の０で初期化   配列名.resize(N)
配列の中身をN個のaで初期化   配列名.assign(N,a)
配列の中からK以上の数字の最小値を出力　lower_bound(配列.begin(),配列.end(),K)
*/
int main(){
    ll N; cin >> N;
    vector<ll> v(N);
    input_vec(v);
    sort(v.begin(),v.end());
    ll su = 0;
    for(int i = 0; i < N; i++){
        su+=v[i];
    }
    vector<vector<pair<ll,ll>>> can(N+1);
    can[0].push_back(make_pair(0,0));
    for(int i = 0; i < N; i++){
        set<ll> check;
        //cout << "o" << endl;
        for(auto a: can[i]){
            //cout << check.size() << endl;
            ll b,c; tie(b,c) = a;
            //cout << b << " ";
            if(!check.count(b))can[i+1].push_back(make_pair(b,c));
            if(!check.count(b+v[i]))can[i+1].push_back(make_pair(b+v[i],c+1));
            check.insert(b);
            check.insert(b+v[i]);
        }
        //cout << endl;
        sort(can[i].begin(),can[i].end());
        
    }
    
    
    ll ans = mod1;
    for(int i = 0; i < N-1; i++){
        ll mx = v[N-1],my = v[i];
        for(auto z: can[i+1]){
            ll a,x; tie(a,x) = z;
            a+=my;
            ll b = su-a;
            x++;
            ll y = N-x;
            //printf("%lld %lld %lld %lld %lld %lld\n",b,mx,a,my,x,y);
            if(my>=a-my||mx>=b-mx)continue;
            if(x<3||y<3) continue;
            ans = min(ans,abs(a-b));
        }
    }
    if(ans == mod1) cout << -1 << endl;
    else cout << ans << endl;
    
}
accuracy: 0.7
time_ms: 10
memory_kb: 3864
final_rank: 13

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template<class T> using vc = vector<T>;
template<class T> using vvc = vc<vc<T>>;
template<class T> using vvvc = vc<vvc<T>>;
template<class T> using vvvvc = vvc<vvc<T>>;
template<class T> using PQ = priority_queue<T>;
template<class T> using invPQ = priority_queue<T, vector<T>, greater<T>>;
using IP = pair<int, int>;
using LP = pair<ll, ll>;
#define all(x) begin(x), end(x)
#define allr(x) rbegin(x), rend(x)
#define rep(i, n) for (int i = 0; (i) < (int)(n); i++)
#define rep3(i, m, n) for (int i = (m); (i) < (int)(n); i++)
#define repr(i, n) for (int i = (n) - 1; (i) >= 0; i--)
#define rep3r(i, m, n) for (int i = (n) - 1; (i) >= (int)(m); i--)
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; }
constexpr long long MOD = 998244353;

void change(IP &p1, IP p2) {
    if (p1 == make_pair(-1, -1)) p1 = p2;
    else {
        if (p1.second > p2.second) p1.second = p2.second;
    }
}

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int N;
    cin >> N;
    vc<int> a(N);
    rep (i, N) cin >> a[i];

    vvvvc<IP> dp(N+1, vvvc<IP>(4001, vvc<IP>(4, vc<IP>(4, {-1, -1}))));
    dp[0][0][0][0] = {0, 0};
    int sum = 0;
    rep (i, N) {
        rep (j, 4001) {
            rep (k, 4) {
                rep (l, 4) {
                    if (dp[i][j][k][l] == make_pair(-1, -1)) continue;
                    change(dp[i+1][j+a[i]][min(3, k+1)][l], make_pair(max(dp[i][j][k][l].first, a[i]), dp[i][j][k][l].second));
                    if (dp[i][j][k][l].first >= a[i]) change(dp[i+1][j][k][min(3, l+1)], make_pair(dp[i][j][k][l].first, max(dp[i][j][k][l].second, a[i])));
                    else change(dp[i+1][sum - j + a[i]][min(3, l+1)][k], make_pair(a[i], dp[i][j][k][l].first));
                }
            }
        }
        sum += a[i];
    }

    int ans = 5000;
    rep (i, 4001) {
        if (dp[N][i][3][3] != make_pair(-1, -1) && dp[N][i][3][3].first < i - dp[N][i][3][3].first && dp[N][i][3][3].second < sum - i - dp[N][i][3][3].second) {
            chmin(ans, abs(i*2-sum));
        }
    }
    if (ans == 5000) cout << -1 << endl;
    else cout << ans << endl;
}
accuracy: 1
time_ms: 40
memory_kb: 56820
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
template<class T> using vc = vector<T>;
template<class T> using vvc = vc<vc<T>>;
template<class T> using vvvc = vc<vvc<T>>;
template<class T> using vvvvc = vvc<vvc<T>>;
template<class T> using PQ = priority_queue<T>;
template<class T> using invPQ = priority_queue<T, vector<T>, greater<T>>;
using IP = pair<int, int>;
using LP = pair<ll, ll>;
#define all(x) begin(x), end(x)
#define allr(x) rbegin(x), rend(x)
#define rep(i, n) for (int i = 0; (i) < (int)(n); i++)
#define rep3(i, m, n) for (int i = (m); (i) < (int)(n); i++)
#define repr(i, n) for (int i = (n) - 1; (i) >= 0; i--)
#define rep3r(i, m, n) for (int i = (n) - 1; (i) >= (int)(m); i--)
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; }
constexpr long long MOD = 998244353;

void change(IP &p1, IP p2) {
    if (p1 == make_pair(-1, -1)) p1 = p2;
    else {
        p1.second = p2.second;
    }
}

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

    int N;
    cin >> N;
    vc<int> a(N);
    rep (i, N) cin >> a[i];

    vvvvc<IP> dp(N+1, vvvc<IP>(4001, vvc<IP>(4, vc<IP>(4, {-1, -1}))));
    dp[0][0][0][0] = {0, 0};
    int sum = 0;
    rep (i, N) {
        rep (j, 4001) {
            rep (k, 4) {
                rep (l, 4) {
                    if (dp[i][j][k][l] == make_pair(-1, -1)) continue;
                    change(dp[i+1][j+a[i]][min(3, k+1)][l], make_pair(max(dp[i][j][k][l].first, a[i]), dp[i][j][k][l].second));
                    if (dp[i][j][k][l].first >= a[i]) change(dp[i+1][j][k][min(3, l+1)], make_pair(dp[i][j][k][l].first, max(dp[i][j][k][l].second, a[i])));
                    else change(dp[i+1][sum - j + a[i]][min(3, l+1)][k], make_pair(a[i], dp[i][j][k][l].first));
                }
            }
        }
        sum += a[i];
    }

    int ans = 5000;
    rep (i, 4001) {
        if (dp[N][i][3][3] != make_pair(-1, -1) && dp[N][i][3][3].first < i - dp[N][i][3][3].first && dp[N][i][3][3].second < sum - i - dp[N][i][3][3].second) {
            chmin(ans, abs(i*2-sum));
        }
    }
    if (ans == 5000) cout << -1 << endl;
    else cout << ans << endl;
}
accuracy: 0.5
time_ms: 40
memory_kb: 56800
final_rank: 14

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;
#define DEBUG
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef pair<int,int> pii;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(int i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<29;
const ll linf = 1LL<<60;
const int MAX = 4020000;
int dy[8] = {0,1,0,-1,1,-1,-1,1};
int dx[8] = {-1,0,1,0,1,-1,1,-1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    int sz = a.size();
    for(auto itr = a.begin(); itr != a.end(); itr++){
		cout << *itr;
        sz--;
        if(sz) cout << " ";
	}
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){
	cout << a << " " << b << "\n";
}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
void mark() {cout << "#" << "\n";}
ll pcount(ll x) {return __builtin_popcountll(x);}
const int mod = 1e9 + 7;
//const int mod = 998244353;

int dp[2][4040][101];

int main(){
	int n; cin >> n;
	int s = 0;
	vector<int> a(n); rep(i,n) cin >> a[i], s += a[i];
	rep(i,2) rep(j,4010) rep(k,101) dp[i][j][k] = inf;
	dp[0][0][0] = 0;
	rep(i,n){
		rep(j,4010) rep(k,101) dp[1][j][k] = inf;
		rep(j,4010){
			rep(k,101){
				if(j+a[i] <= 4010) chmin(dp[1][j+a[i]][max(k,a[i])], dp[0][j][k]);
				if(dp[0][j][k] <= 100) chmin(dp[1][j][k], max(a[i], dp[0][j][k]));
			}
		}
		swap(dp[0], dp[1]);
	}
	int ans = inf;
	rep(j,4010) rep(k,101){
		if(j <= 2*k || s-j <= 2*dp[0][j][k]) continue;
		chmin(ans, abs(s-j-j));
	}
	if(ans == inf) ans = -1;
	cout << ans << "\n";
}
accuracy: 1
time_ms: 30
memory_kb: 6308
final_rank: 4

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using VI = vector<int>;
using VL = vector<ll>;
using VS = vector<string>;
template<class T> using PQ = priority_queue<T, vector<T>, greater<T>>;
#define FOR(i,a,n) for(int i=(a);i<(n);++i)
#define eFOR(i,a,n) for(int i=(a);i<=(n);++i)
#define rFOR(i,a,n) for(int i=(n)-1;i>=(a);--i)
#define erFOR(i,a,n) for(int i=(n);i>=(a);--i)
#define SORT(a) sort(a.begin(),a.end())
#define rSORT(a) sort(a.rbegin(),a.rend())
#define fSORT(a,f) sort(a.begin(),a.end(),f)
#define all(a) a.begin(),a.end()
#define out(y,x) ((y)<0||h<=(y)||(x)<0||w<=(x))
#define tp(a,i) get<i>(a)
#ifdef _DEBUG
#define line cout << "-----------------------------\n"
#define stop system("pause")
#endif
constexpr ll INF = 1000000000;
constexpr ll LLINF = 1LL << 60;
constexpr ll mod = 1000000007;
constexpr ll MOD = 998244353;
constexpr ld eps = 1e-10;
constexpr ld pi = 3.1415926535897932;
template<class T>inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; }return false; }
template<class T>inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; }return false; }
inline void init() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(15); }
template<class T>inline istream& operator>>(istream& is, vector<T>& v) { for (auto& a : v)is >> a; return is; }
template<class T, class U>inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template<class T>inline vector<T> vec(size_t a) { return vector<T>(a); }
template<class T>inline vector<T> defvec(T def, size_t a) { return vector<T>(a, def); }
template<class T, class... Ts>inline auto vec(size_t a, Ts... ts) { return vector<decltype(vec<T>(ts...))>(a, vec<T>(ts...)); }
template<class T, class... Ts>inline auto defvec(T def, size_t a, Ts... ts) { return vector<decltype(defvec<T>(def, ts...))>(a, defvec<T>(def, ts...)); }
template<class T>inline void print(const T& a) { cout << a << "\n"; }
template<class T, class... Ts>inline void print(const T& a, const Ts&... ts) { cout << a << " "; print(ts...); }
template<class T>inline void print(const vector<T>& v) { for (int i = 0; i < v.size(); ++i)cout << v[i] << (i == v.size() - 1 ? "\n" : " "); }
template<class T>inline void print(const vector<vector<T>>& v) { for (auto& a : v)print(a); }
inline string reversed(const string& s) { string t = s; reverse(all(t)); return t; }
template<class T>inline T sum(const vector<T>& a, int l, int r) { return a[r] - (l == 0 ? 0 : a[l - 1]); }
template<class T>inline void END(T s) { print(s); exit(0); }
void END() { exit(0); }

int main() {
    init();

    int n; cin >> n;
    VI a(n); cin >> a;
    SORT(a);
    int s = accumulate(all(a), 0);

    auto dp = vec<bool>(n + 1, n + 1, 4001);
    dp[0][0][0] = true;
    FOR(i, 0, n)FOR(j, 0, n)eFOR(k, 0, 4000) {
        if (!dp[i][j][k])continue;
        if (k + a[i] <= 4000)
            dp[i + 1][j + 1][k + a[i]] = true;
        dp[i + 1][j][k] = true;
    }

    int ans = INF;
    FOR(i, 0, n)eFOR(j, 2, n - 4)eFOR(k, 0, 4000) {
        if (!dp[i][j][k])continue;
        if (a[i] < k && a[n - 1] < (s - a[i] - k) - a[n - 1])
            chmin(ans, abs(a[i] + k - (s - a[i] - k)));
    }
    print(ans == INF ? -1 : ans);

    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 4028
final_rank: 2

code_snippet: #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define repr(i, n) for (int i = (n); i--;)
#define all(x) x.begin(), x.end()
using ll = long long;

template <class T, class U>
bool chmin(T& x, U y) {
    if (x > y) {
        x = y;
        return true;
    } else {
        return false;
    }
}

template <class T, class U>
bool chmax(T& x, U y) {
    if (x < y) {
        x = y;
        return true;
    } else {
        return false;
    }
}

bool bit_at(const int& mask, int pos) {
    return (mask >> pos) & 1;
}

struct Rec {
    int sum;
    int max;
    int xam;
    bool operator<(const Rec& rhs) const {
        return sum < rhs.sum;
    }
};

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

    int n; std::cin >> n;
    int middle = n / 2;
    std::vector<int> a(n); rep(i, n) std::cin >> a[i];
    int total = std::accumulate(a.begin(), a.end(), 0);
    int target = total / 2;

    auto f = [&](int l, int w) {
        std::vector<Rec> pt;
        rep(mask, 1 << w) {
            int sum = 0, max = 0, xam = 0;
            rep(i, w) if (bit_at(mask, i)) {
                sum += a[l + i];
                chmax(max, a[l + i]);
            } else {
                chmax(xam, a[l + i]);
            }
            pt.emplace_back(Rec { sum, max, xam });
        }
        return pt;
    };

    auto lf = f(0, middle);
    auto pt = f(middle, n - middle);
    sort(pt.begin(), pt.end());

    int res = INT_MAX;
    for (Rec rec : lf) {
        int choice = target - rec.sum;
        int hit = std::lower_bound(all(pt), Rec { choice, 0, 0 }) - pt.begin();
        for (int i = std::max(0, hit - 100); i < std::min<int>(pt.size(), hit + 100); i++) {
            Rec cer = pt[i];
            int sum = rec.sum + cer.sum;
            int max = std::max(rec.max, cer.max);
            int xam = std::max(rec.xam, cer.xam);
            if (sum > 2 * max && sum < total - 2 * xam) {
                chmin(res, abs(total - 2 * sum));
            }
        }
    }

    if (res == INT_MAX) res = -1;
    std::cout << res << "\n";
}
accuracy: 1
time_ms: 580
memory_kb: 33604
final_rank: 11

code_snippet: #include <iostream>
#include <set>
#include <vector>
#include <algorithm>

using namespace std;
struct E{
	int c,m1,m2,l;
	bool operator<(const E& e1)const{
		if(c!=e1.c)return c<e1.c;
		if(m1!=e1.m1)return m1<e1.m1;
		if(m2!=e1.m2)return m2<e1.m2;
		return l<e1.l;
	}
};
set<E> ss[42];
vector<int> vs;
int main() {
	// your code goes here
	int n;
	cin>>n;
	int sum=0;
	for(int i=0;i<n;i++){
		int t;
		cin>>t;
		vs.push_back(t);
		sum+=t;
	}
	sort(vs.begin(),vs.end());
	E e;
	e.c=0;
	e.m1=0;
	e.m2=0;
	e.l=0;
	ss[0].insert(e);
	for(int i=0;i<n;i++){
		int t=vs[i];
		for(auto it=ss[i].begin();it!=ss[i].end();it++){
			E e1=(*it);
			E e2=(*it);
			e1.m1=t;
			e1.l+=t;
			e1.c=e1.c+1;
			ss[i+1].insert(e1);
			e2.m2=t;
			ss[i+1].insert(e2);
		}
	}
	int ans=-1;
	for(auto it=ss[n].begin();it!=ss[n].end();it++){
		E e=(*it);
		bool b1=(e.c>2);
		bool b2=((n-e.c)>2);
		bool b3=(e.l-e.m1>e.m1);
		bool b4=((sum-e.l-e.m2)>e.m2);
		int t2=abs(e.l-(sum-e.l));
		if(b1&&b2&&b3&&b4){
			if(ans==-1){
				ans=t2;
			}else{
				
				if(ans>t2)ans=t2;
			}
		}
	}
	cout<<ans<<"\n";
	return 0;
}
accuracy: 1
time_ms: 300
memory_kb: 98184
final_rank: 12

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

using namespace std;

#define int long long

const int INF = (1<<30);

int solve2(vector<int>& L){
	int res = INF;
	int N = L.size();
	int NUM = 101;
	
	sort(L.begin(), L.end(), greater<int>());
	
	int con = 0;
	
	
	for(int i = 0; i < N; i++){
		for(int j = i+1; j < N; j++){
			for(int l = j+1; l <= N; l++){
				int sum1 = 0, sum2 = 0;
				int MAX = NUM*(N-l+3);
				int sum = 0, con1 = 0, con2 = 0, con3 = 0;
				vector<int> dp(MAX);
				dp[0] = true;
				
				
				for(int k = 0; k < N; k++){
					if(k <= i) sum1 += L[k], con1++;
					else if(k <= j) sum2 += L[k], con2++;
					else if(k <= l) sum1 += L[k], con1++;
					else if(k == l+1) sum2 += L[k], con2++;
					else {
						for(int m = MAX-1; m >= 0; m--){
							if(dp[m]) dp[m + L[k]] = true;
						}
						sum += L[k];
						con3++;
					}
				}
				
				for(int m = MAX-1, flag = false; m >= 0; m--){
					if(dp[m]){
						if(!m){
							if(con1 >= 3 && con2+con3 >= 3 &&L[0] < (sum1+m) - L[0] && L[i+1] < (sum2+sum-m) - L[i+1]){
								res = min(res, abs((sum1+m)-(sum2+sum-m)));
							}
						} else if(flag){
							if(L[0] < (sum1+m) - L[0] && L[i+1] < (sum2+sum-m) - L[i+1]){
								res = min(res, abs((sum1+m)-(sum2+sum-m)));
							}
						} else {
							sum = m;
							flag = true;
							if(con1+con3 >= 3 && con2 >= 3 &&L[0] < (sum1+m) - L[0] && L[i+1] < (sum2+sum-m) - L[i+1]){
								res = min(res, abs((sum1+m)-(sum2+sum-m)));
							}
						}
					}
				}
			}
		}
	}
	
	return res==INF?-1:res;
}

signed main(){
	int N;
	vector<int> l;
	
	cin>>N;
	
	l.resize(N);
	
	for(int i = 0; i < N; i++){
		cin>>l[i];
	}

	cout<<solve2(l)<<endl;
	
}
accuracy: 1
time_ms: 130
memory_kb: 3188
final_rank: 6

code_snippet: #include <bits/stdc++.h>
#define all(vec) vec.begin(), vec.end()
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
constexpr ll INF = (1LL << 30) - 1LL;
constexpr ll LINF = (1LL << 60) - 1LL;
constexpr ll MOD = 1e9 + 7;
template <typename T> void chmin(T &a, T b) { a = min(a, b); }
template <typename T> void chmax(T &a, T b) { a = max(a, b); }
int dp[41][4010][41][4];
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<int> a(n);
    int sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }
    sort(all(a));
    for (int i = 0; i <= 40; i++) {
        for (int j = 0; j <= 4000; j++) {
            for (int k = 0; k <= 40; k++) {
                for (int l = 0; l < 4; l++) {
                    dp[i][j][k][l] = -INF;
                }
            }
        }
    }
    dp[n - 1][a[n - 1]][n][1] = 0;
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j <= 4000; j++) {
            for (int k = n; k > i; k--) {
                for (int l = 0; l <= 3; l++) {
                    if (j >= a[i] && l > 0) {
                        chmax(dp[i][j][k][l], dp[i + 1][j - a[i]][k][l - 1]);
                        if (l == 3) {
                            chmax(dp[i][j][k][l], dp[i + 1][j - a[i]][k][l]);
                        }
                    }
                    if (k != n) {
                        chmax(dp[i][j][k][l], dp[i + 1][j][k][l] + 1);
                    }
                }
            }
            for (int l = 0; l <= 3; l++) {
                chmax(dp[i][j][i][l], dp[i + 1][j][n][l] + 1);
            }
        }
    }
    int res = INF;
    for (int i = 0; i <= 4000; i++) {
        if (i - a[n - 1] <= a[n - 1]) {
            continue;
        }
        for (int j = 0; j < n; j++) {
            if (dp[0][i][j][3] >= 3 && sum - i - a[j] > a[j]) {
                chmin(res, abs(i - (sum - i)));
            }
        }
    }
    if (res == INF) {
        cout << -1 << endl;
        return 0;
    }
    cout << res << endl;
}

/*
dp[i][j][k][l]:i番目までにおいて、Am=Anなる多角形の長さの和がjでl個選んで、もう一つがAm=Akのときのそれの最大数
状態:40*4000*40*9,遷移O(1)
*/
accuracy: 1
time_ms: 60
memory_kb: 108468
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#define all(vec) vec.begin(), vec.end()
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
constexpr ll INF = (1LL << 30) - 1LL;
constexpr ll LINF = (1LL << 60) - 1LL;
constexpr ll MOD = 1e9 + 7;
template <typename T> void chmin(T &a, T b) { a = min(a, b); }
template <typename T> void chmax(T &a, T b) { a = max(a, b); }
int dp[41][4010][41][4];
int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<int> a(n);
    int sum = 0;
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        sum += a[i];
    }
    sort(all(a));
    for (int i = 0; i <= 40; i++) {
        for (int j = 0; j <= 4000; j++) {
            for (int k = 0; k <= 40; k++) {
                for (int l = 0; l < 4; l++) {
                    dp[i][j][k][l] = -INF;
                }
            }
        }
    }
    dp[n - 1][a[n - 1]][n][1] = 0;
    for (int i = n - 2; i >= 0; i--) {
        for (int j = 0; j <= 4000; j++) {
            for (int k = n; k > i; k--) {
                for (int l = 0; l <= 3; l++) {
                    if (j >= a[i] && l > 0) {
                        chmax(dp[i][j][k][l], dp[i + 1][j - a[i]][k][l - 1]);
                        if (l == 3) {
                            chmax(dp[i][j][k][l], dp[i + 1][j - a[i]][k][l]);
                        }
                    }
                    chmax(dp[i][j][k][l], dp[i + 1][j][k][l] + 1);
                }
            }
            for (int l = 0; l <= 3; l++) {
                chmax(dp[i][j][i][l], dp[i + 1][j][n][l] + 1);
            }
        }
    }
    int res = INF;
    for (int i = 0; i <= 4000; i++) {
        if (i - a[n - 1] <= a[n - 1]) {
            continue;
        }
        for (int j = 0; j < n; j++) {
            if (dp[0][i][j][3] >= 3 && sum - i - a[j] > a[j]) {
                chmin(res, abs(i - (sum - i)));
            }
        }
    }
    if (res == INF) {
        cout << -1 << endl;
        return 0;
    }
    cout << res << endl;
}

/*
dp[i][j][k][l]:i番目までにおいて、Am=Anなる多角形の長さの和がjでl個選んで、もう一つがAm=Akのときのそれの最大数
状態:40*4000*40*9,遷移O(1)
*/
accuracy: 0.2
time_ms: 30
memory_kb: 108396
final_rank: 15

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;



int N;
int LEN[45];
bool dp[45][4005];

int main(){

	scanf("%d",&N);

	int maximum = 0,max_index;
	int total = 0;

	for(int i = 0; i < N; i++){

		scanf("%d",&LEN[i]);

		total += LEN[i];

		if(maximum < LEN[i]){
			maximum = LEN[i];
			max_index = i;
		}
	}

	int ans = BIG_NUM;

	for(int another_max = 0; another_max < N; another_max++){ //39
		if(another_max == maximum)continue;

		//maximumを含まない方の作成可能な周長
		for(int num = 1; num <= N-1; num++){
			for(int sum = LEN[another_max]; sum <= total-maximum; sum++){
				dp[num][sum] = false;
			}
		}

		dp[1][LEN[another_max]] = true; //another_maxを必ず含むので、0はtrueにしない

		for(int i = 0; i < N; i++){
			if(i == max_index || i == another_max || LEN[i] > LEN[another_max])continue;

			for(int num = i+1; num >= 1; num--){
				for(int sum = LEN[another_max]; sum <= total-maximum; sum++){
					if(!dp[num][sum])continue;

					dp[num+1][sum+LEN[i]] = true;
					if(num+1 >= 3 && (N-(num+1)) >= 3){
						if(LEN[another_max] < sum+LEN[i]-LEN[another_max]){
							int rest = total-(sum+LEN[i]);
							if(maximum < rest-maximum){

								ans = min(ans,abs(rest-(sum+LEN[i])));
							}
						}
					}
				}
			}
		}
	}

	if(ans == BIG_NUM){

		printf("-1\n");
	}else{

		printf("%d\n",ans);
	}

	return 0;
}
accuracy: 1
time_ms: 70
memory_kb: 3380
final_rank: 5