akhauriyash/Code-Regression huggingface dataset:
#include <stdio.h>
#include <stdlib.h>
 
typedef char                SINT8;
typedef unsigned char       UINT8;
typedef short               SINT16;
typedef unsigned short      UINT16;
typedef int                 SINT32;
typedef unsigned int        UINT32;
typedef long long           SINT64;
typedef unsigned long long  UINT64;
 
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
#define ABS(a) ((a)>(0)?(a):-(a))
 
 
SINT32 main() {
    SINT32 n,q;
    scanf("%d%d",&n,&q);
 
 
    SINT32 kazu[200001] = {0};
    SINT8 s[200001] = {'0'};
 
    SINT8 t[200001] = {'0'};
    SINT8 d[200001] = {'0'};
 
    scanf("%s",s);
 
    for (SINT32 i = 0; i < q; i++) {
        scanf("%s%s",&t[i],&d[i]);
    }



    SINT32 count = 0;
    SINT32 count2 = 0;
    SINT32 r = n - 1;

    for (SINT32 i = q-1; i >= 0; i--) {
        if (d[i] == 'R') {
            if (s[count-1] == t[i]) {
                count--;
            }
            if (s[r] == t[i]) {
                r--;
            }

        } else {
            if (s[r+1] == t[i]) {
                r++;
            }
            if (s[count] == t[i]) {
                count++;
            }
        }
 //       printf("%d %d\n",count,r);
    }





    if (r < 1) {count2 = 0;}
    else {count2 = r-count+1;}
 
    printf("%d\n",count2);
	return 0;
}


Measured memory_bytes: 768
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include <bitset>
#include<math.h>
using namespace std;
#define INF 11000000000
#define MOD 1000000007
typedef long long ll;
typedef pair<string,int> P;

ll C[30];

int main(){
    ll n,m,d,pa;
    cin>>n>>m>>d;

    if(d!=0) pa=n-d+n-d;
    else pa=n;
    
    double ans=(double)pa*(m-1)/(n*n);
    //cout<<pa<<endl;
    printf("%.12f\n",ans);
}


Measured memory_bytes: 256
while true
    rect = gets.split.map(&:to_i)
    break if (rect[0] == 0 && rect[1] == 0)
    tate = rect[0]/2
    yoko = rect[1]/2
    
    if rect[0] % 2 == 0 && rect[1] % 2 == 0 then
        tate.times do
            puts '#.'*yoko
            puts '.#'*yoko
        end
    end

    if rect[0] % 2 == 1 && rect[1] % 2 == 0 then
        tate.times do
            puts '#.'*yoko
            puts '.#'*yoko
        end
        puts '#.'*yoko
    end
    
    if rect[0] % 2 == 0 && rect[1] % 2 == 1 then
        tate.times do
            print '#.'*yoko
            puts "#"
            print '.#'*yoko
            puts "."
        end
    end
    
    if rect[0] % 2 == 1 && rect[1] % 2 == 1 then
        tate.times do
            print '#.'*yoko
            puts "#"
            print '.#'*yoko
            puts "."
        end
        print '#.'*yoko
        puts "#"
    end
    
    puts
    
end

Measured memory_bytes: 6124
#include<bits/stdc++.h>
using namespace std;

int main(){
  int k,x;
  cin >> k >> x;
  for(int i=max(-1000000,x-k+1);i<min(x+k,1000000);i++){
    cout << i;
    if(i!=x+k-1&&i!=1000000)
      cout << " ";
  }
  cout << endl;
  return 0;
}

Measured memory_bytes: 3652
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
struct lpl{
	int x, y, id;
	bool operator < (const lpl &A)const{return (x == A.x) ? (y < A.y) : (x < A.x);}
	bool operator <= (const lpl &A)const{return (x == A.x) ? (y <= A.y) : (x < A.x);}
}point[maxn], lower;
struct ld{
	int x, y;
	bool operator < (const ld &A)const{return (x == A.x) ? (y < A.y) : (x < A.x);}
};
int fa[maxn];
long long ans[maxn], siz[maxn];
int n, a, b, d;
map<ld, int> mp;

int find(int t){return (t == fa[t]) ? (t) : (fa[t] = find(fa[t]));}

inline void connect(int a, int b){
	a = point[a].id; b = point[b].id;
	a = find(a); b = find(b); fa[a] = b;
}

inline void workk(){
	int L = 0, R = 0;
	sort(point + 1, point + n + 1);
	for(int i = 1; i <= n; ++i){
		lower.x = point[i].x - d; lower.y = point[i].y - d;
		int lin = lower_bound(point + 1, point + n + 2, lower) - point;
		L = max(lin, R); R = L; 
		if(point[L].x == lower.x && point[L].y <= point[i].y + d) 
			connect(i, L);
		while(point[R + 1].x + d == point[i].x && point[R + 1].y <= point[i].y + d){
			connect(R, R + 1); R++;
		}
		ans[point[i].id] += (R - lin + 1); 
		if(point[lin].x != lower.x || point[lin].y > point[i].y + d) ans[point[i].id]--;
	}
}

inline void check(){
	for(int i = 1; i <= n; ++i) printf("i = %d x = %d y = %d\n", i, point[i].x, point[i].y);
	printf("\n");
}

int main()
{
	//freopen("lpl.in", "r", stdin);
	scanf("%d%d%d", &n, &a, &b); point[n + 1].x = point[n + 1].y = 2e9;
	for(int x, y, i = 1; i <= n; ++i){
		scanf("%d%d", &x, &y);
		point[i].x = x + y; point[i].y = x - y; point[i].id = i;
		mp[(ld){point[i].x, point[i].y}]++;
	}
	d = max(abs(point[a].x - point[b].x), abs(point[a].y - point[b].y));
	for(int i = 1; i <= n; ++i){
		if(mp[(ld){point[i].x - d, point[i].y - d}]) ans[i]--;
		if(mp[(ld){point[i].x - d, point[i].y + d}]) ans[i]--;
	}
	for(int i = 1; i <= n; ++i) fa[i] = i;
	//check();
	workk();
	//printf("d = %d\n", d);
	//for(int i = 1; i <= n; ++i) printf("ans[%d] = %lld\n", i, ans[i]);
	for(int i = 1; i <= n; ++i) swap(point[i].x, point[i].y);
	//check();
	workk();
	//for(int i = 1; i <= n; ++i) printf("ans[%d] = %lld\n", i, ans[i]);
	//for(int i = 1; i <= n; ++i) printf("fa[%d] = %d\n", i, find(i));
	for(int i = 1; i <= n; ++i) siz[find(i)] += ans[i];
	cout << siz[find(a)];
	return 0;
}

Measured memory_bytes: 22144
#include <numeric>
#include <iostream>
#include <sstream>
#include <vector>
#include <cstdio>
#include <map>
#include <set>
#include <functional>
#include <queue>
#include <string>
#include <bitset>
#include <cassert>
#include <algorithm>
#include <cmath>
#include <set>
#include <algorithm>
#include <tuple>
#include <sstream>

using namespace std;

#ifdef LOCAL
#define logv(a) {cerr << #a << " = "; for (auto& e : a) {cerr << e << " ";} cerr << "\n";}
#define logvp(a) {cerr << #a << " = "; for (auto& e : a) {cerr << "(" << e.first << ", " << e.second << ") ";} cerr << "\n";}
#define logvv(a) {cerr << #a << " = \n"; for (auto& r : a) { for (auto& e : r) {cerr << e << " ";} cerr << "\n";} }
#define logvf(a, field) {cerr << #a"."#field << " = \n"; for (auto& e : a) { cerr << e.field << " ";} cerr << "\n"; }
#define logs(a) cerr << #a << " = " << (a) << "\n";
#define logss(a, b) cerr << #a << " = " << (a) << ", " << #b << " = " << (b) << "\n";
#define logp(a) cerr << #a << " = " << "(" << a.first << ", " << a.second << ")" << "\n";
#define cond(pred, stmt) if (pred) { stmt }
#else
#define logv(a)
#define logvp(a)
#define logvv(a)
#define logvf(a, field)
#define logs(a)
#define logss(a, b)
#define logp(a)
#define cond(pred, stmt)
#endif

#define forn(a, e) for (int a = 0; a < (int)e; a++)
#define forr(a, s, e) for (int a = s; a < (int)e; a++)

using i64 = long long;

template<typename T>
using Pair = array<T, 2>;

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

    string s;
    while (cin >> s) {
        string t;
        cin >> t;
        int c = 0;
        forn(i, s.size()) {
            if (s[i] == t[i]) {
                c++;
            }
        }
        cout << c << endl;
    }
}


Measured memory_bytes: 256
#include<stdio.h>

int main(void)
{
	int a,b;
	
	scanf("%d %d",&a,&b);
	
	if(a<b){
		printf("a < b\n");
	}
	else if(a>b){
		printf("a > b\n");
	}
	else{
		printf("a == b\n");
	}
	
	return(0);
}

Measured memory_bytes: 580
N = int(input())
dp = [0] * (N + 1)
for i in range(1, N+1):
    dp[i] = float('inf')
    power = 1
    while power <= i:
        dp[i] = min(dp[i], dp[i - power] + 1)
        power *= 6
    power = 1
    while power <= i:
        dp[i] = min(dp[i], dp[i - power] + 1)
        power *= 9
print(dp[N])

Measured memory_bytes: 3828
#include <iostream>
#include <string>

using namespace std;


class A {
	int n, m;

public:
	void solve()
	{
		cin >> n >> m;

		cout << (n - 1) * (m - 1) << endl;
	}
};

class B {
	string s;

public:
	void solve()
	{
		cin >> s;

		cout << s.front() << s.length() - 2 << s.back() << endl;
	}

};

int main()
{
	A solution;
	solution.solve();
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;

int main() {
	int a[3];
	cin >> a[0] >> a[1] >> a[2];
	sort(a, a + 3);
	int ans = abs(a[0] - a[1]) + abs(a[1] - a[2]);
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ordered_set tree<pair<int,int>, null_type,less<pair<int,int>>, rb_tree_tag,tree_order_statistics_node_update>
using namespace std;
using namespace __gnu_pbds;
#define int long long int
#define pb push_back
#define vec vector<int>
#define fo(i, n) for (int i = 0; i < n; i++)
#define foo(i, a, b) for (int i = a; i < b; i++)
#define mp make_pair
#define deb(x) cout << #x << " --> " << x << endl;

#define deb1a(v)                  \
    cout << #v << "--->" << endl; \
    for (auto it : v)             \
        cout << it << " ";        \
    cout << endl;
#define deb2a(v)                  \
    cout << #v << "--->" << endl; \
    for (auto it : v)             \
    {                             \
        for (auto it1 : it)       \
        {                         \
            cout << it1 << " ";   \
        }                         \
        cout << endl;             \
    }
#define deb3a(v) cout << #v << "-->" << endl; for(auto it:v){\
cout << it.fi << " " << it.se << endl;}


#define mod 1000000007
#define so(v) sort(v.begin(),v.end())
#define fi first
#define se second
//#define endl "\n"
int power(int x, unsigned int y, int p){ int res = 1;x = x % p;while (y > 0)  { if (y & 1)res = (res*x) % p;y = y>>1;  x = (x*x)% p;} return res;}
int mI(int a, int m)  {return power(a, m - 2, m);}



int32_t main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    set<string> ss;
    int n;
    cin >> n;
    fo(i,n){
        string s;
        cin >> s;
        ss.insert(s);
    }
    cout << ss.size();
}

Measured memory_bytes: 19184
//include
//------------------------------------------
#include <bits/stdc++.h>
using namespace std;

//typedef
//------------------------------------------
typedef long long LL;
typedef vector<LL> VL;
typedef vector<VL> VVL;
typedef vector<string> VS;
typedef pair<LL, LL> PLL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);
const int MOD = 1000000007;

//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

//main code

int main(int argc, char const* argv[])
{
	LL n,k;
	cin >> n >> k;
	VL x(n);
	for (int i = 0; i < n; i++) {
		cin >> x[i];
	}
	LL ans = INT64_MAX;
	for (int i = 0; i < n-k+1; i++) {
		LL l = abs(x[i]), r = abs(x[i+k-1]);
		if (x[i] * x[i+k-1] < 0) {
			ans = min(ans,min(2*l+r,l+2*r));
		}
		else {
			ans = min(ans,max(l,r));
		}
		cerr << i << ": " << ans << endl;
	}
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 1024
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <random>
#include <iomanip>
#include <functional>
#include <cassert>
 
using namespace std;
 
typedef long long ll;
 
int main() {
  ios_base::sync_with_stdio(false); cin.tie(0);
#ifdef LOCAL
  freopen("input.txt", "r", stdin);
#endif
  int n, k;
  cin >> n >> k;
  string s;
  cin >> s;
  s += 'B';
  ++n;
  deque <int> lens;
  int len = 1;
  for (int i = 1; i < n; ++i) {
    if (s[i] != s[i - 1]) {
      lens.push_back(len);
      len = 1;
    } else {
      ++len;
    }
  }
  lens.push_back(len);
  char c = s[0];
  auto go = [&] () {
    if (c == 'A') {
      int x = lens.front();
      lens.pop_front();
      if (x == 1) {
        ++lens.front();
      } else {
        lens.push_front(x - 1);
        lens.push_front(1);
      }
      c = 'B';
    } else {
      int x = lens.front();
      lens.pop_front();
      lens.push_back(1);
      if (x > 1) {
        lens.push_front(x - 1);
        c = 'A';
      }
    }
  };  
  for (int i = 0; i < k; ++i) {
    go();
    if ((int)lens.size() == n && c == 'B') {
      break;
    }
    if ((int)lens.size() == n && c == 'A') {
      if ((k - i - 1) % 2 == 1) {
        go();
      }
      break;
    }
  }
  string ans;
  for (auto l : lens) {
    for (int i = 0; i < l; ++i) ans += c;
    if (c == 'A') c = 'B';
    else c = 'A';
  }
  ans.pop_back();
  cout << ans << '\n';
}
 


Measured memory_bytes: 1944
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void) {
  int a, b, c, d;
  scanf("%d%d%d%d", &a, &b, &c, &d);
  if (abs(a-c) <= d || (abs(a-b) <= d && abs(b-c) <= d)) {
    puts("Yes");
  } else {
    puts("No");
  }

  return 0;
}


Measured memory_bytes: 128
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    if(a+b+c >= 22) puts("bust");
    else puts("win");
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
using namespace std;

int main(){

    int N,M;
    cin >> N >> M;
    int a[M],b[M];
    int bw[N],k = 0;
    for(int i = 0;i<M;i++){
        cin >> a[i] >> b[i];
        /*
        if(a[i] == 1){
            b1[k] = b[i];
            k ++;
        }
        */
    }
    for(int i = 0;i<N;i++) bw[i] = 0;

    bool flag = false;

    for(int i = 0;i<M;i++){
        if(a[i] == 1){
            if(bw[b[i]] == 1){
                flag = true;
                break;
            }
            else bw[b[i]] = 1; 
        }

        if(b[i] == N){
            if(bw[a[i]] == 1){
                flag = true;
                break;
            }
            else bw[a[i]] = 1;
            /*
            for(int j = 0;j<k;j++){
                if(a2 == b1[j]){
                    flag = true;
                    break;
                }
            }
            */
        }
    }

    if(flag) cout << "POSSIBLE" << endl;
    else cout << "IMPOSSIBLE" << endl;

    return 0;
}

Measured memory_bytes: 2560
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations
import sys
import bisect
import string
import math
import time
from fractions import gcd
#import random


def I(): return int(input())


def MI(): return map(int, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YN = ['Yes', 'No']
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)


# show_flg = False
show_flg = True


def main():
    S = input()
    T = input()
    canditates = []

    for i in range(len(S)):
        idx = 0
        for j in range(i, len(S)):
            if idx < len(T) and (S[j] == T[idx] or S[j] == '?'):
                idx += 1
            else:
                break

        # print(idx, S, len(T))
        if idx == len(T):
            canditates.append(S[:i] + T + S[i+len(T):])
            # print(S[:i], T, S[i+len(T):])
            # print(i, i+len(T))

    if len(canditates) > 0:
        # print(canditates)
        canditates = [c.replace("?", "a") for c in canditates]
        canditates.sort()
        print(canditates[0])
    else:
        print("UNRESTORABLE")

if __name__ == '__main__':
    main()


Measured memory_bytes: 5588
#include <bits/stdc++.h>
// statics
using namespace std;
using int64 = long long;
using PAIR = pair<int, int>;
constexpr int INF = 1 << 30;
constexpr int64 LINF = 1LL << 60;
constexpr int MOD = 1e9 + 7;

// init/input
#define int int64
#define INIT ios::sync_with_stdio(false);cin.tie(0);
#define VAR(type, ...) type __VA_ARGS__;MACRO_VAR_Scan(__VA_ARGS__);
template<typename T> void MACRO_VAR_Scan(T &t) {cin>>t;}
template<typename First, typename...Rest> void MACRO_VAR_Scan(First &first, Rest&...rest) {cin>>first;MACRO_VAR_Scan(rest...);}
#define VEC(type, c, n) vector<type> c(n);for(auto &&i:c)cin>>i;

// out
#define OUT(dist) cout<<(dist);
#define FOUT(n, dist) cout <<fixed<<setprecision(n)<<(dist);
#define SP cout<<" ";
#define BR cout<<"\n";

// utility
#define ALL(a) (a).begin(), (a).end()
#define EACH(i, a) for(auto &&i:(a))
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define RFOR(i, a, b) for(int i=(b)-1;i>=0;--i)
#define REP(i, n) for(int i=0;i<(n);++i)
#define RREP(i, n) for(int i=(n)-1;i>=0;--i)

template< class Abel > class BIT {
public:
  BIT() : N(0) {}
  // 以下[1, N]なので+1する必要がある(1-indexed)
  BIT(int n) : N(n), bit(N + 1, 0) {}
  BIT(int n, Abel init) : N(n), bit(N + 1, init) {}

  void add(int i, Abel x) {
    i++;
    // for (int t = ++i; t < N; t += t & -t) bit[t] += x;
    while (i <= N) { bit[i] += x; i += i & -i; }
  }

  Abel sum(int i) {
    Abel res = 0; int t = i;
    while (t > 0) {
      res += bit[t];
      t -= t & -t;
    }
    return res;
  }

  // [i, j)の半開区間
  Abel sum(int i, int j) {
    return sum(j) - sum(i);
  }

private:
  int N;
  vector< Abel > bit;
};

int n;
vector< int > x;

bool check(int mid_n) {
  vector< int > b(n);
  REP(i, n) b[i] = (x[i] >= mid_n) ? 1 : -1;
  
  vector< int > sm(n + 1, n);
  REP(i, n) sm[i + 1] = sm[i] + b[i];
  
  BIT< int > bit(2 * n);
  
  int res = 0;
  RREP(i, n + 1) {
    res += bit.sum(sm[i], 2 * n);
    bit.add(sm[i], 1);
  }
  
  return res >= (n * (n + 1) / 2 + 1) / 2;
}

signed main() {
  INIT;

  cin >> n;
  x.resize(n);
  EACH(xi, x) cin >> xi;
  
  if (n == 1) {
    OUT(x[0])BR;
    return 0;
  }
  
  int ok = 0, ng = 1e9 + 1;
  while (abs(ng - ok) > 1) {
    int mid = (ok + ng) / 2;
    if (check(mid)) ok = mid;
    else ng = mid;
  }
  OUT(ok)BR;
  return 0;
}


Measured memory_bytes: 4236
#include <iostream>

using namespace std;

#define repd(i,a,b) for (int i=(a);i<(b);++i)
#define rep(i,n) repd(i,0,n)
typedef long long ll;

int main(){
  int n;
  int k;
  cin >> n;
  cin >> k;
  int ans = 0;
  rep(i, n){
    int x;
    cin >> x;
    ans += min(x, k-x);
  }
  cout << ans*2 << endl;
  return 0;
}


Measured memory_bytes: 504
N = int(input())
arr = [int(input()) for i in range(N)]
arr.sort()
m = N // 2

if N % 2 ==0:
  high = sum(arr[m:])
  low  = sum(arr[:m])
  print((high - low) * 2 - (arr[m] - arr[m-1]))
else:
  center = arr[m]
  high = sum(arr[m+1:])
  low = sum(arr[:m])
  dl = center - arr[m-1]
  dh = arr[m+1] - center
  if dl > dh:
    print((high - low) * 2 - dh)
  else:
    print((high - low) * 2 - dl)

Measured memory_bytes: 7488
#include <bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define erep(i,a,b) for(int i=a;i<=(int)(b);++i)
#define per(i,a,b) for(int i=(a);i>(b);--i)
#define eper(i,a,b) for(int i=(a);i>=b;--i)
#define fore(x, a) for(auto &x : a)
#define pb push_back
#define mp make_pair
#define INF 100100100100
#define inf 2001001001
#define MOD 1000000007
#define ALL(x) begin(x),end(x)
#define F first
#define S second

using namespace std;
using ll = long long;
using pii = pair<int,int>;
using vii = vector<int>;
using vll = vector<ll>;
template<class T>using vv = vector<T>;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a = b; return 1; } return 0; }
template<class T>void show(const vector<T> &a) { for (int i = 0; i < (int)a.size(); ++i) cout << a[i] << (i != (int)a.size()-1 ? " " : "\n"); }
template<class T>T gcd(T a, T b){ return b ? gcd(b, a % b) : a; }
template<class T>T lcm(T a, T b){ return a / gcd(a, b) * b; }
int dy[]={0, 1, -1, 0};
int dx[]={1, 0, 0, -1};

int c[3][3];
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
    rep(i, 0, 3) rep(j, 0, 3) cin >> c[i][j];
    int a[3], b[3];
    rep(a1, 0, 101) {
      rep(a2, 0, 101) {
        rep(a3, 0, 101) {
          a[0] = a1, a[1] = a2, a[2] = a3;
          rep(i, 0, 3) b[i] = c[0][i] - a[0];
          bool flag = true;
          rep(i, 0, 3) {
            rep(j, 0, 3) {
              if (c[i][j] != a[i] + b[j]) flag = false;
            }
          }
          if (flag) {
            cout << "Yes" << endl;
            return 0;
          }
        }
      }
    }
    cout << "No" << endl;
    return 0;
}



Measured memory_bytes: 256
N = int(input()) 
ans = 111111111110
for i in range(1,int(N**0.5+2)):
    if N%i == 0:
        use = N//i 
        s = str(use) 
        t = str(i) 
        ans = min(ans, max(len(s), len(t))) 

print(ans)

Measured memory_bytes: 9424
#include<bits/stdc++.h>
#define rep(i,n) for(ll i=0;i< (n);i++)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;

int main(){
    ll n;cin>>n;
    vector<ll> lst;
    map<ll,ll> A;
    set<ll> s;
    rep(i,n){
        ll tmp;cin>>tmp;
        lst.push_back(tmp);
        A[tmp]++;
        s.insert(tmp);
    }
    ll ans = 0;
    for(ll h:s){
        ans += A[h]*(A[h]-1)/2;
    }
    rep(i,n){
        ll tg = lst[i];
        ll x = A[tg];
        cout<<ans-(x-1)<<endl;
    }
    return 0;
}

Measured memory_bytes: 17008
a, b, c = map(int, input().split())
m = max([a, b, c])
x = [m - i for i in [a, b, c]]
x.sort(reverse=True)
d = x[0] + x[1]
if d % 2 == 0:
    print(d // 2)
else:
    print((d + 1) // 2 + 1)


Measured memory_bytes: 3060
N = int(input())

p = [0] * (N+1)

for i in range(2, N+1):
    for j in range(2, i+1):
        cnt = 0
        while i % j == 0:
            cnt += 1
            i //= j
        p[j] += cnt

def get_sum(n): return len(list(filter(lambda x: x >= n-1, p)))

print(get_sum(75) + get_sum(25)*(get_sum(3)-1) + get_sum(15)*(get_sum(5)-1)
    + get_sum(5)*(get_sum(5)-1)*(get_sum(3)-2)//2)

Measured memory_bytes: 3064
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define pb push_back
#define INF 0x3f3f3f3
#define LINF 0x3f3f3f3f3f3f3f
#define MAXN int(2*1e3+5)
#define fim '\n'
#define ll long long
#define f first
#define s second
#define FAST cin.tie(0), cout.tie(0), ios::sync_with_stdio(0)
#define debug(x) cout << "DEBUG " << x << fim
#define debug2(x, y) cout << "DEBUG " << x << " " << y << fim
#define debug3(x, y, z) cout << "DEBUG " << x << " " << y << " " << z<< fim
#define max3(x, y, z) max(x, max(y, z))
using namespace std;
using namespace __gnu_pbds;
typedef pair<int, int> pii;
typedef pair<string, int> psi;
typedef pair<unsigned ll, pair<int, int> > piii;
typedef pair<pair<int, int>, int> piii2;
typedef tree<int,null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update> indexed_set;

int vet[MAXN], k[MAXN], dist[MAXN], n;
vector<int > g[MAXN];
priority_queue<pii, vector<pii>, greater<pii> > fila;
bool used[MAXN];

void bfs() {

    for(int i = 1; i <= n; i++)
        dist[i] = INF;

    dist[1] = 0;

    while(!fila.empty()) {

        pii atual = fila.top();
        fila.pop();


        if(used[atual.s])
            continue;

        used[atual.s] = 1;

        for(auto i : g[atual.s]) {
            dist[i] = min(atual.f+1, dist[i]);
            if(!used[i])
                fila.push({atual.f+1, i});

        }

    }
}
int main() {
    int x, y;
    cin >> n >> x >> y;
    for(int i = 1; i <= n; i++) {
        g[i].pb(i+1);
        g[i+1].pb(i);
    }
    g[x].pb(y);
    g[y].pb(x);
    ll ans = 0;
    fila.push({0, 1});
    bfs();

    for(int i = 1; i <= n; i++)
        for(int j = i+1; j <= n; j++) {
            if(i > x) {
                int xd = min(j-i, (i-x)+dist[j]-dist[x]);
                k[xd]++;
                continue;
            }
            k[abs(dist[i]-dist[j])]++;
        }
    for(int i = 1; i <= n-1; i++)
        cout << k[i] << endl;
}


Measured memory_bytes: 384
#include<bits/stdc++.h>
using namespace std;

typedef long long LL;

const int N = 2e5;
const LL INF = 1e7;

int n;
int h[N+5];
LL a[N+5];

LL ST[4*N+5];

void build(int node=1, int l=1, int r=n){
	if(l==r){
		ST[node] = -INF;
		return;
	}
	build(node*2,l,(l+r)/2);
	build(node*2+1,(l+r)/2+1,r);
	ST[node] = max(ST[node*2],ST[node*2+1]);
	return;
}

void update(int node, int l, int r, int pos, LL val){
	if(l>pos || r<pos) return;
	if(l==r){
		ST[node] = val;
		return;
	}
	update(node*2,l,(l+r)/2,pos,val);
	update(node*2+1,(l+r)/2+1,r,pos,val);
	ST[node] = max(ST[node*2],ST[node*2+1]);
	return;
}

LL query(int node, int l, int r, int ql, int qr){
	if(l>qr || r<ql) return -INF;
	if(l>=ql && r<=qr) return ST[node];
	return max(query(node*2,l,(l+r)/2,ql,qr) , query(node*2+1,(l+r)/2+1,r,ql,qr));
}

int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&h[i]);
	for(int i=1;i<=n;i++) scanf("%lld",&a[i]);
	build();
	LL ans = 0LL;
	for(int i=1;i<=n;i++){
		LL tmp = max(0LL,query(1,1,n,1,h[i]));
		tmp+=a[i];
//		cout << tmp << endl;
		ans = max(ans,tmp);
		update(1,1,n,h[i],tmp);
	}
	printf("%lld\n",ans);
	return 0;
}

Measured memory_bytes: 8832
//{{{
#include <bits/stdc++.h>
using namespace std;
#define rep(...) repN((__VA_ARGS__,rep3,rep2,loop,~))(__VA_ARGS__)
#define loop(n) rep2(_loop_,n)
#define rep2(i,n) rep3(i,0,n)
#define rep3(i,begin,end) for(int i=(int)(begin),i##_end=(int)(end);i<i##_end;++i)
#define repN(a) repX a
#define repX(a0,a1,a2,x,...) x
#define foreach(x,a) for(auto &x:a)
typedef long long ll;
const ll MOD = 1e9+7;
//}}}

int main(){
  ll H, W;
  cin >> H >> W;

  if(H % 3 == 0 || W % 3 == 0){
    cout << 0 << endl;
    return 0;
  }
  ll ans = 1e18;
  ll Smin;
  ll Smax;
  ll S1;
  ll S2;
  ll S3;
  rep(x, 2){
    rep(i, 1, W){
      S1 = i * H;
      S2 = H / 2 * (W - i);
      S3 = (H - H / 2) * (W - i);
      Smin = min(min(S1, S2), S3);
      Smax = max(max(S1, S2), S3);
      ans = min(Smax - Smin, ans);
    }
    swap(H, W);
  }
  ans = min(min(W, H), ans);
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 256
def examA():
    H1, M1, H2, M2, K = LI()
    T = (H2-H1)*60 + (M2-M1)
    ans = T-K
    print(ans)
    return

def examB():
    T = SI()
    ans = ""
    for t in T:
        if t=="?":
            ans += "D"
        else:
            ans += t
    print(ans)
    return

def examC():
    N = I()
    A = LI()
    check = 1<<N
    for i,a in enumerate(A):
        check -= (1<<(N-i))*a
    if check<0:
        print(-1)
        return
    ans = 0
    cnt = 1
    less = sum(A)
    for i in range(N+1):
        a = A[i]
        if cnt>less:
            cnt = less
        ans += cnt
        less -= a
        cnt = (cnt-a)*2
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examC()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Measured memory_bytes: 93252
#include <bits/stdc++.h>

using namespace std;

int main(){
  int n;
  cin >> n;
  int a[n];
  int m = 0, ans = 0;
  for(int i = 0;i < n;i++){
    cin >> a[i];
    m = max(m,a[i]);
  }
  
  bool b = false;
  for(int i = 1;i <= m;i++){
    for(int j = 0;j < n;j++){
      if(!b && a[j] >= i) b = true;
      if(b && a[j] < i){
        b = false;
        ans++;
      }
    }
    if(b) {
      ans++;
      b = false;
    }
  }
  
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 3628
//#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
#define rep(i, n) for(int i=0; i<n; ++i)
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
using namespace std;
using ll = int64_t;
using ld = long double;
using P = pair<int, int>;
using vs = vector<string>;
using vi = vector<int>;
using vvi = vector<vi>;
const int INF = 100010001;
const ll LINF = (ll)INF*INF*10;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int q;
    cin >> q;
    set<int> se;
    while(q--) {
        int t, x;
        cin >> t >> x;
        if(t == 0) {
            se.insert(x);
            cout << se.size() << '\n';
        } else if(t == 1) {
            auto itr = se.find(x);
            cout << (itr != se.end()) << '\n';
        } else {
            se.erase(x);
        }
    }
}


Measured memory_bytes: 12608
#include <iostream>
#include <vector>
#include <map>

using namespace std;

int n, m;
int a[100000];
int cumsum[100000];
map<int, int> hist;
int main(){
    cin >> n >> m;

    long long ans = 0;
    cumsum[0] = 0;
    hist[0] = 1;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    long long sm = 0;
    for (int i = 0; i < n; ++i) {
        sm += a[i];
        cumsum[i + 1] = a[i] + cumsum[i];
        cumsum[i + 1] %= m;
        int k = cumsum[i + 1];
        int rest = k;
        if (hist.find(rest) != hist.end()) {
            ans += hist[rest];
        }
        if (hist.find(k) != hist.end()) {
            hist[k] += 1;
        } else {
            hist[k] = 1;
        }
    }

    cout << ans << endl;
}

Measured memory_bytes: 3968
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        
        Scanner sc = new Scanner(System.in);
        int H =sc.nextInt();
        int W =sc.nextInt();
        int h =sc.nextInt();
        int w =sc.nextInt();
        
        System.out.println((H-h)*(W-w));
    }
}


Measured memory_bytes: 22612
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cassert>
#include <cctype>
using namespace std;
typedef long long lint;
#define cout cerr
#define ni (next_num<int>())
template<class T>inline T next_num(){
	T i=0;char c;
	while(!isdigit(c=getchar())&&c!='-');
	bool flag=c=='-';
	flag?(c=getchar()):0;
	while(i=i*10-'0'+c,isdigit(c=getchar()));
	return flag?-i:i;
}
const int dN=5010,O=1000000007;
inline int fpow(int x,int n){
	lint a=1;
	for(;n;n>>=1,x=(lint)x*x%O){
		if(n&1){
			a=(lint)a*x%O;
		}
	}
	return a;
}
inline int inv(int x){
	return fpow(x,O-2);
}
int fact[dN],fs=0;
lint f[dN];
inline void addfact(int x,int e){
	for(int i=0,j=0;i<e;i++){
		for(int k=fs;j<k;j++){
			fact[fs++]=fact[j]*x;
		}
	}
}
int main(){
	int n=ni,k=ni;
	fact[fs++]=1;
	for(int x=2,e;x*x<=n;x++){
		for(e=0;n%x==0;n/=x,e++);
		addfact(x,e);
	}
	if(n!=1){
		addfact(n,1);
	}
	lint ans=0;
	for(int i=0;i<fs;i++){
		int d=fact[i];
		f[i]=fpow(k,(d+1)>>1);
		for(int j=0;j<i;j++){
			if(d%fact[j]==0){
				f[i]-=f[j];
			}
		}
		f[i]=(f[i]%O+O)%O;
		static int inv2=inv(2);
		ans+=d&1?f[i]*d%O:(f[i]*d%O*inv2%O);
	}
	printf("%lld\n",ans%O);
	return 0;
}

Measured memory_bytes: 256
import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    //nextLineとnextを同時に使ったら死ぬ
    val sc = new Scanner(System.in)
    val xa, xb, ya, yb = sc.nextInt()
    val x = ya - xa
    val y = yb - xb
    println(s"${ya - y} ${yb + x} ${xa - y} ${xb + x}")
  }
}


Measured memory_bytes: 25768
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
	ios_base::sync_with_stdio(0); 
    cin.tie(0);   
	ll n,m,k,b[200009],a[200009],c=0,sum=0,up1,up2,ma=0;
	string s;
	cin>>n>>m>>k;
	vector <ll> a1,b1;
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		if(i>0)
			a[i]+=a[i-1];
		a1.push_back(a[i]);
	}
	for(int i=0;i<m;i++)
	{
		cin>>b[i];
		if(i>0)
			b[i]+=b[i-1];
		b1.push_back(b[i]);
	}
	up1=upper_bound(a1.begin(),a1.end(),k)-a1.begin();
	up2=upper_bound(b1.begin(),b1.end(),k-a[up1-1])-b1.begin();
	ma=up1+up2;
	// cout<<up1<<" "<<up2<<" "<<a[up1]<<endl;
	for(int i=up1;i>=0;i--)
	{
		up2=upper_bound(b1.begin(),b1.end(),k-a[i-1])-b1.begin();
		ma=max(i+up2,ma);
		// cout<<i<<" "<<up2<<endl;
	}
	up1=upper_bound(b1.begin(),b1.end(),k)-b1.begin();
	up2=upper_bound(a1.begin(),a1.end(),k-b[up1-1])-a1.begin();
	ma=max(up1+up2,ma);
	for(int i=up1;i>=0;i--)
	{
		up2=upper_bound(a1.begin(),a1.end(),k-b[i-1])-a1.begin();
		ma=max(i+up2,ma);
	} 
	cout<<ma<<endl;
	return 0;
}

Measured memory_bytes: 10564
#include<bits/stdc++.h>

using namespace std;
using ll = long long;


int main()
{
    string s; cin >> s;
    int n = s.size();
    for(int i = 0; i < n - 1; i++) {
        if(i != n - 2) {
            string ss = s.substr(i, 3);
            if(ss[0] == ss[1] || ss[1] == ss[2] || ss[0] == ss[2]) {
                cout << i + 1 << " " << i + 3 << endl;
                return 0;
            }
        }
        string ss = s.substr(i, 2);
        if(ss[0] == ss[1]) {
            cout << i + 1 << " " << i + 2 << endl;
            return 0;
        }
    }
    cout << -1 << " " << -1 << endl;
}

Measured memory_bytes: 512
from sys import setrecursionlimit
from collections import Counter
from collections import defaultdict
from collections import deque
from heapq import heapify
from heapq import heappop
from heapq import heappush
from time import time
setrecursionlimit(10**9)
mod=10**9+7
inf=10**18

x=int(input())

print(0 if x== 1 else 1)

Measured memory_bytes: 9452
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
	int n, k, ans = 1;
	scanf("%d%d", &n, &k);
	for (int i = 0; i < n; i++)
	{
		if (ans * 2 > ans + k) {
			ans += k;
		}
		else
		{
			ans *= 2;
		}
	}
	printf("%d", ans);
	return 0;
}

Measured memory_bytes: 128
#include <stdio.h>
int main(void){
  int n, ans=0, temp=0, i, x;
  scanf("%d", &n);
  for(i=1;i<=n;i++){
    x=i;
    while(x!=0){
      x/=10;
      temp++;
    }
    if(temp%2==1){
      ans++;
    }
    temp=0;
  }
  printf("%d\n", ans);
  return 0;
}


Measured memory_bytes: 128
import sys
import os
import heapq
N,M = map(int,input().split())

if N>=M:
    print(0)
    sys.exit()

X = list(map(int,input().split()))
X.sort()

Q = []
for i in range(M-1):
    heapq.heappush(Q,(-(X[i+1]-X[i]),i))

sum = 0
for i in range(1,N):
    sum = sum + (-heapq.heappop(Q)[0])
print(X[M-1]-X[0]-sum)

Measured memory_bytes: 17356
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
 
 
void swap (int *x, int *y) {
  int temp;    
 
  temp = *x;
  *x = *y;
  *y = temp;
}
 
int gcd(int a,int b){
  if(a<b){
    swap(&a,&b);
  }
 
  if(b==0){
    return a;
  }
 
  int r=a%b;
  while(r!=0){
    a = b;
    b = r;
    r = (a%b);
  }
 
  return b;
}
 
/* クイックソート */
int dn(const void*a,const void*b){return*(int*)b-*(int*)a;}
 
 
int modpow(int a,int n,int mod){
  int ans=1;
  while(n>0){
    if(n & 1){
      ans=ans*a%mod;
    }
    a=a*a%mod;
    n/=2;
  }
  return ans;
}
 
int max(int a,int b){
  if(a<b){
    return b;
  }
  else{
    return a;
  }
}
 
int min(int a,int b){
  if(a<b){
    return a;
  }
  else{
    return b;
  }
}
 
void chmax(int *a,int b){
  if(*a < b){
    *a = b;
  }
 
  return;
}
 
void chmin(int *a,int b){
  if(*a > b){
    *a =b;
  }
 
  return;
}
 

int main(void){
  int s;
  scanf("%d",&s);
  int x,y;
  y=s%100;
  x=(s-y)/100;
  if(0<x && x<13){
    if(0<y && y<13){
      printf("AMBIGUOUS\n");
    }
    else if(0<=y && y<100){
      printf("MMYY\n");
    }
  }else if(0<y && y<13){
    if(0<=x && x<100){
      printf("YYMM\n");
    }
  }else{
    printf("NA\n");
  }
  return 0;
}

Measured memory_bytes: 1640
#include<bits/stdc++.h>
using namespace std;

int main()
{
     int n,i;
     long long  sum=0;

     cin>>n;

     for(i = 1; i <= n; i++)
     {
          if(i%3==0 && i%5==0)
               sum=sum;
          else if(i%3==0)
               sum==sum;
          else if(i%5==0)
               sum==sum;
               else
                    sum+=i;

     }
     cout<<sum<<endl;
}


Measured memory_bytes: 3636
#include<bits/stdc++.h>
using namespace std;

int main(void){
   int N,M;
   cin>>N>>M;
   vector<int> a(M),b(M);
   for(int i=0;i<M;i++){
      cin>>a[i]>>b[i];
      a[i]--;
      b[i]--;
   }
   vector<vector<int>> graph(N);
   for(int i=0;i<M;i++){
      graph[a[i]].push_back(b[i]);
   }
   string ans="IMPOSSIBLE";
   for(auto x:graph[0]){
      for(auto y:graph[x]){
         if(y==N-1){
            ans="POSSIBLE";
            break;
         }
      }  
   }
   cout<<ans<<endl;
   return 0;
}

Measured memory_bytes: 10112
#include <bits/stdc++.h>
using namespace std;

#define DEBUG(x) cerr << #x << ": " << x << endl;
#define ll long long

int main() {
    map<int, int> mpa, mpb;

    int A;
    cin >> A;
    vector<int> a;
    for (int i = 0; i < A; i++) {
        int x;
        scanf("%d", &x);
        a.push_back(x);
    }

    int B;
    cin >> B;
    vector<int> b;
    for (int i = 0; i < B; i++) {
        int x;
        scanf("%d", &x);
        b.push_back(x);
    }

    for (int i = 0; i < A; i++) {
        mpa[a[i]]++;
    }

    for (int i = 0; i < B; i++) {
        mpb[b[i]]++;
    }

    for (int i = 0; i < B; i++) {
        int x = b[i];
        if (mpb[x] > mpa[x]) {
            cout << "NO" << endl;
            return 0;
        }
    }

    cout << "YES" << endl;

    return 0;
}

Measured memory_bytes: 20596
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vs = vector<string>;
using msi = map<string, int>;
using mii = map<int, int>;
using psi = pair<string, int>;
using pii = pair<int, int>;
using vlai = valarray<int>;
#define rep(i,n) for(int i=0;i<n;i++)
#define range(i,s,n) for(int i=s;i<n;i++)
#define all(a) a.begin(),a.end()
#define rall(a) a.rbegin(),a.rend()
#define fs first
#define sc second
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define INF (ll)1E9
#define EPS 1E-9
#define MOD 1000000007
#define PI 3.1415926535897932384

template <class T>ostream &operator<<(std::ostream &o, const vector<T> &v)
{
	rep(i, v.size()) {
		o << (i > 0 ? " " : "") << v[i];
	}
	return o;
}

//int dx[]={1,1,1,0,-1,-1,-1,0},dy[8]={1,0,-1,-1,-1,0,1,1,1};

int main() {
	int n,ans=INF;
	cin >> n;
	range(i, 1, n) {
		int tmp = 0;
		int a = i, b = n - a;
		while (a) {
			tmp += (a % 10);
			a /= 10;
		}
		while (b) {
			tmp += (b % 10);
			b /= 10;
		}
		ans = min(ans,tmp);
	}
	cout << ans << endl;
	
}


Measured memory_bytes: 256
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <complex>
#include <utility>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <tuple>
#include <cmath>
#include <bitset>
#include <cctype>
#include <set>
#include <map>
#include <unordered_map>
#include <numeric>
#include <functional>
#define _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(ll i=ll(a);i<ll(b);++i)
#define rep(...) _overload3(__VA_ARGS__,repi,_rep,)(__VA_ARGS__)
#define all(x) (x).begin(),(x).end()
#define PRINT(V) cout << V << "\n"
#define SORT(V) sort((V).begin(),(V).end())
#define RSORT(V) sort((V).rbegin(), (V).rend())
using namespace std;
using ll = long long;
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; }
inline void Yes(bool condition){ if(condition) PRINT("Yes"); else PRINT("No"); }
template<class itr> void cins(itr first,itr last){
    for (auto i = first;i != last;i++){
        cin >> (*i);
    }
}
template<class itr> void array_output(itr start,itr goal){
    string ans = "",k = " ";
    for (auto i = start;i != goal;i++) ans += to_string(*i)+k;
    if (!ans.empty()) ans.pop_back();
    PRINT(ans);
}
ll gcd(ll a, ll b) {
    return a ? gcd(b%a,a) : b;
}
const ll INF = 1e15;
const ll MOD = 1000000007;
const ll MOD2 = 998244353;
typedef pair<ll,ll> P;
const ll MAX = 2010;
constexpr ll nx[8] = {1,0,-1,0,-1,-1,1,1};
constexpr ll ny[8] = {0,1,0,-1,-1,1,-1,1};
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll n,m;
    cin >> n >> m;
    vector<ll> v(n);
    cins(all(v));
    ll ans = 0;
    rep(i,n+1){
        rep(j,n-i+1){
            if (i+j > m) continue;
            vector<ll> g;
            rep(k,i){
                g.push_back(v[k]);
            }
            rep(k,j){
                g.push_back(v[n-k-1]);
            }
            SORT(g);
            ll c = 0;
            rep(k,i+j) c += g[k];
            rep(k,min(m-i-j,i+j)){
                if (g[k] < 0){
                    c -= g[k];
                }
            }
            chmax(ans,c);
        }
    }
    PRINT(ans);
}


Measured memory_bytes: 256
import sys
sys.setrecursionlimit(10**6)

N, M = map(int, input().split())
p = list(map(int, input().split()))
xy = []
for _ in range(M):
    xy.append(tuple(map(int, input().split())))
#print(xy)


G = [[] for _ in range(N+1)]
for el in xy:
    x, y = el
    G[x].append(y)
    G[y].append(x)


seen=[False] * (N+1)
def dfs(n):
    seen[n]=True
    group[-1].append(n)
    for child in G[n]:
        if seen[child] == False:
            dfs(child)

group=[]
for i in range(1,N+1):
    if seen[i] == False:
        group.append([])
        dfs(i)
        #print(seen)
#print(seen)
#print(group)

cnt = 0
for el in group:
    temp = set(el) & set([p[i-1] for i in el])
    cnt += len(temp)
print(cnt)


Measured memory_bytes: 87272
#include <bits/stdc++.h>

#define fr first
#define sc second
#define int long long
#define forn(i, x, n) for (int i = x; i < (int)n; ++i)
#define all(x) x.begin(), x.end()
#define endl '\n'
#define pb push_back

using namespace std;

const int MAXN = 1e5 + 2, INF = 1e14 + 19, MAXLOG = 18;
const double EPS = 1e-5;

typedef vector<int> vi;
typedef pair<int, int> pii;
const int MXSH = 201;

main() {
//    freopen("input.txt", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int n, a, b;
    cin >> n >> a >> b;
    vi mas(n);
    forn(i, 0, n) {
        cin >> mas[i];
    }
    int l = 0, r = INF;
    a = a - b;
    while(r - l > 1) {
        int mid = (l + r) / 2;
        vi kek;
        forn(i, 0, n) {
            if (mid * b >= mid && mid * b >= b) {
                int x = mas[i] - mid * b;
                if (x > 0) {
                    kek.pb(x);
                }
            }
        }
        int c = 0;
        for (int i : kek) {
            c += ((i + a - 1) / a);
        }
        if (c > mid) {
            l = mid;
        } else {
            r = mid;
        }
    }
    cout << r;
}


Measured memory_bytes: 2916
#include<bits/stdc++.h>
#define MN 2000
using namespace std;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
char st[1000005];
int n,K,lt[MN+5],rt[MN+5],yes[MN+5];
bitset<1000001> b[26],S;
bitset<10005> f[MN+5],can;
bool Solve(int x,int len)
{
    if(((S<<1)&b[x]).any()) return true;
    for(int i=1,flag=0;i<=n;++i)
    {
        if(S[rt[i-1]]) flag=1;
        if(flag&&st[lt[i]]-'a'<=x&&f[i][len]) return true;
    }
    return false;
}
int main()
{  
    n=read();K=read();
    for(int i=1,len=0;i<=n;++i) 
    {
        scanf("%s",st+len+1);
        lt[i]=len+1,rt[i]=(len+=strlen(st+len+1));
        for(int j=lt[i]+1;j<=rt[i];++j) b[st[j]-'a'][j]=1;
    }
    can[K]=1;
    for(int i=n;i;--i) f[i]=can>>(rt[i]-lt[i]+1),can|=f[i];
    for(int i=1;i<26;++i) b[i]|=b[i-1];S[0]=1;
    for(int i=1;i<=K;++i)
    {
        int l=0,r=24,mid,res=25;
        while(l<=r)
        {
            mid=l+r>>1;
            if(Solve(mid,i-1)) res=mid,r=mid-1;
            else l=mid+1;
        }
        for(int j=1,flag=0;j<=n;++j)
        {
            if(S[rt[j-1]]) flag=1;
            if(flag&&st[lt[j]]-'a'==res&&f[j][i-1]) yes[j]=1;
            else yes[j]=0;
        }
        putchar(res+'a');S=(S<<1)&b[res];
        for(int j=1;j<=n;++j) if(yes[j]) S[lt[j]]=1;
    }
    return 0;
}

Measured memory_bytes: 7680
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void scan(T...)(ref T a) {
    string[] ss = readln.split;
    foreach (i, t; T) a[i] = ss[i].to!t;
}
T read(T)() { return readln.chomp.to!T; }
T[] reads(T)() { return readln.split.to!(T[]); }
alias readint = read!int;
alias readints = reads!int;

int[] calc(int N, int Y) {
    // x + y + z = N
    // 10,000 * x + 5,000 * y + 1,000 * z = Y
    // 上を 10,000 倍して、下から引くと、
    // 5,000 * y + 9,000 * z = 10,000 * N - Y
    // y をループ回して固定化して、z を求める:
    // z = (10,000 * N - Y - 5,000 * y) / 9,000

    for (int y = 0; y <= N; y++) {
        int z = 10000 * N - Y - 5000 * y;
        if (z < 0 || z % 9000 != 0) continue;

        z /= 9000;
        int x = N - (y + z);
        if (x >= 0 && x + y + z == N)
            return [x, y, z];
    }
    return [-1, -1, -1];
}

void main() {
    int N, Y; scan(N, Y);

    auto ans = calc(N, Y);
    writeln(ans.map!(text).join(" "));
}


Measured memory_bytes: 256
#include <stdio.h>  
#include <algorithm>  
#include <bitset>
#include <cassert>
#include <ctime>  
#include <cmath>  
#include <cstdlib>  
#include <cstring>  
#include <functional>  
#include <iostream>  
#include <deque>  
#include <stack>
#include <queue>  
#include <vector>  
#include <map>  
#include <set>  
#include <string>  
#include <unordered_map>  
#include <unordered_set>  

using namespace std;

#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define endl '\n'

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, int> pdi;

const ll INF = 1e18;
const int MAXN = 3e5 + 5;

ll a, b, c;

int main() {
	ios::sync_with_stdio(0); cin.tie(0);
	cin >> a >> b;
	if(a == 1 || b == 1) cout << 1;
	else cout << (a*b+1)/2;
}



Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;

public static class Solution
{
    static long GetMax(List<long> list, long K)
    {
        var N = list.Count;
        var cycleScore = list.Sum();
        list = list.Concat(list).ToList();

        long score = 0;
        if (cycleScore > 0)
        {
            var m = K / N;
            if (K % N == 0)
            {
                m--;
            }
            score += cycleScore * m;
            K -= m * N;
        }
        if (K > 0)
        {
            long max = long.MinValue;
            for (int l = 0; l < N; l++)
            {
                var sum = list[l];
                for (int r = l + 1; r < N * 2 && r - l <= K; r++)
                {
                    max = Math.Max(max, sum);
                    sum += list[r];
                }
            }
            score += max;
        }
        return score;
    }

    static long Solve(int N, long K, int[] P, long[] C)
    {
        var seqs = new List<List<long>>();
        var visited = new bool[N];
        for (int i = 0; i < N; i++)
        {
            if (visited[i])
            {
                continue;
            }

            var list = new List<long>();
            var cur = i;
            while (!visited[cur])
            {
                visited[cur] = true;
                list.Add(C[cur]);
                cur = P[cur];
            }
            seqs.Add(list);
        }

        var max = seqs.Max(s => GetMax(s, K));
        return max;
    }

    public static void Main()
    {
        var vals = Console.ReadLine().Split(' ').Select(long.Parse).ToArray();
        var N = (int)vals[0];
        var K = vals[1];
        var P = Console.ReadLine().Split(' ').Select(x => int.Parse(x) - 1).ToArray();
        var C = Console.ReadLine().Split(' ').Select(long.Parse).ToArray();

        var max = Solve(N, K, P, C);
        Console.WriteLine(max);
    }
}

Measured memory_bytes: 29672