akhauriyash/Code-Regression huggingface dataset:
const modP = 1000000007;
var Kcomb,NKcomb,inv:array[0..2010]of int64;
    i,j,k,a,b,n,m,p:int64;
    
begin
  readln(n,k);
  
  inv[1]:=1;
  for i:=2 to k do begin
    inv[i]:=1;
    p:=modP-2;
    j:=i;
    while p>0 do begin
    if (p and 1)>0 then inv[i]:=inv[i]*j mod modP;
      j:=j*j mod modP;
      p:=p >> 1;
    end;
  end;
  
  m:=n-k+1;
  NKcomb[0]:=1; NKcomb[m]:=1;
  Kcomb[0]:=1; Kcomb[k-1]:=1;
  for i:=1 to (k+1)div 2 do begin
    Kcomb[i]:=Kcomb[i-1]*(k-i)mod modP*inv[i] mod modP ;
    Kcomb[k-1-i]:=Kcomb[i];
  end;
  for i:=1 to (m+1)div 2 do begin
    NKcomb[i]:=NKcomb[i-1]*(m-i+1)mod modP*inv[i] mod modP;
    NKcomb[m-i]:=NKcomb[i];
  end;
  
  for i:=1 to k do begin
    if i<=n-k+1 then begin
      b:=NKcomb[i] * Kcomb[i-1] mod modP;
      writeln(b);
    end else writeln(0);
  end;
  
end.


Measured memory_bytes: 128
#include <bits/stdc++.h>
#define int long long
#define N 200011

using namespace std;

int n, ans, h[N], a[N], dp[N];

/* ----- Segment Tree ----- */
int st[N << 1];

void update(int p, int val) {
	for(st[p += n] = val; p > 1; p >>= 1) 
		st[p>>1] = max(st[p], st[p^1]);
}

int query(int l, int r) {
	int res = 0;
	for(l += n, r += n; l < r; l >>= 1, r >>= 1) {
		if(l&1) res = max(res, st[l++]);
		if(r&1) res = max(res, st[--r]);
	}
	return res;
}

signed main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	cin >> n;
	for(int i=0; i<n; i++) cin >> h[i];
	for(int i=0; i<n; i++) cin >> a[i];
	for(int i=n-1; i>=0; i--) {
		if(i == n-1) dp[i] = a[i];
		else dp[i] = query(h[i], n+1) + a[i];
		ans = max(ans, dp[i]);
		update(h[i], dp[i]);
	}
	cout << ans << endl;
	return 0;
}

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

const long long INF = 1LL << 60;
int MOD = 1000000007;
double PI = 3.14159265358979323846;
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; }

typedef long long ll;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<(int)(n);i++)
#define rrep(i,n) for(int i=(int)(n)-1;i>=0;i--)
#define For(i,s,n) for (int i=s;i<(int)(n);i++)
#define vi vector<int>
#define vii vector< vector<int> >
#define vs vector<string>
#define All(c) (c).begin(), (c).end()
#define Print(x) cout<<(x)<<"\n"


//B

int main() {

	int N; cin >> N;
	int A[110000];
	rep(i, N) cin >> A[i];
	int ans = 0;

	rep(i, N) {
		if (A[A[i] - 1] == i + 1) ans +=1;
	}
	cout << ans/2 << endl;
}

Measured memory_bytes: 4032
t=list(map(int,input().split(' ')))
n=t[0] ; k=t[1]
x=0
for i in range(k,n+2):
    p=i*(2*n-(i-1))/2
    q=i*(i-1)/2
    x+=(p-q+1)
print(int(x)%(10**9+7))

Measured memory_bytes: 9216
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;

class Plan
{
public:
	int num, cnt;
};

class GreaterCnt
{
public:
	bool operator() (const Plan& lhs, const Plan& rhs)
	{
		if (lhs.cnt == rhs.cnt)
			return lhs.num < rhs.num;
		return lhs.cnt > rhs.cnt;
	}
};

int main()
{
	int n, m;
	while (scanf("%d %d", &n, &m) != EOF) {
		if (n == 0 && m == 0)
			break;

		vector<Plan> p(m);
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < m; ++j) {
				p[j].num = j+1;
				int t;
				scanf("%d", &t);
				if (t == 1)
					++p[j].cnt;
			}
		}

		sort(p.begin(), p.end(), GreaterCnt());

		for (unsigned int i = 0; i < p.size()-1; ++i)
			printf("%d ", p[i].num);
		printf("%d\n", p.back().num);
	}
	return 0;
}

Measured memory_bytes: 0
#include<bits/stdc++.h>
#define rep(i,n) for (int i = 0; i< (n); ++i)
using namespace std;
using ll = long long;
#define ALL(a) sort((a).begin(), (a).end())
#define PB push_back

int main(){
    int N,x;
    cin >> N >> x;
    vector<int> a(N);
    rep(i,N){
        cin >> a.at(i);
    }
    ALL(a);
    int ans = 0;
    for(int i=0;i<N;i++){
        x -= a.at(i);
        if(x == 0){
            ans++;
            break;
        }else if(x < 0){      
            break;
        }else{
            ans++;
            if(i == N-1){
               break;
            }
        }
    }
    if(x > 0 && ans == N){
        ans --;
    }
    
    cout << ans << endl;
}





Measured memory_bytes: 256
#![allow(dead_code)]
#![allow(unused_imports)]
use ascii::{AsciiChar, AsciiStr, AsciiString};
use indexmap::IndexMap;
use itertools::*;
use libm::*;
use num::*;
use ordered_float::OrderedFloat;
use permutohedron::LexicalPermutation;
use proconio::marker::{Bytes, Chars};
use proconio::{fastout, input};
use std::cmp::{max, min, Ordering};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::mem::swap;

fn main() {
    input!(a:char);
    match a {
        'a'...'z' => println!("a",),
        _ => println!("A"),
    }
}


Measured memory_bytes: 2080
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <functional>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <deque>
#include <list>
#include <sys/timeb.h>
#include <fstream>
#include <set>

using namespace std;

#define repr(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define rep(i,n) repr(i,0,n)
#define reprrev(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);i--)
#define reprev(i,n) reprrev(i,0,n)
#define repi(itr,ds) for(auto itr=ds.begin();itr!=ds.end();itr++)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define mp make_pair
#define mt make_tuple
#define INF 1050000000
#define INFL 1100000000000000000LL
#define EPS (1e-10)
#define MOD 1000000007
#define PI 3.1415926536
#define RMAX 4294967295

typedef long long ll;
typedef pair<int, int> Pi;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<Pi> vPi;
typedef vector<vector<int> > vvi;
typedef vector<vector<bool> > vvb;
typedef vector<vector<ll> > vvll;
typedef vector<vector<char> > vvc;
typedef vector<vector<string> > vvs;
typedef vector<vector<double> > vvd;
typedef vector<vector<Pi> > vvPi;
typedef priority_queue<int, vector<int>, greater<int> > pqli;
typedef priority_queue<ll, vector<ll>, greater<ll> > pqlll;
typedef priority_queue<Pi, vector<Pi>, greater<Pi> > pqlP;
struct Edge {
	int from, to, cost;
	bool operator<(Edge e) {
		return cost < e.cost;
	}
};
typedef vector<Edge> Edges;
typedef vector<Edges> Graph;
template <class T>
using vec = vector<T>;
template<class T>
using pql = priority_queue<T, vector<T>, greater<T>>;
string debug_show(Pi a) {
	return "(" + to_string(a.first) + "," + to_string(a.second) + ")";
}

template<class T>
struct augEdge {
	T from, to;
	int cost;
	bool operator<(augEdge e) { return cost < e.cost; }
	bool operator>(augEdge e) { return cost > e.cost; }
};
template<class T>
using augGraph = vector<augEdge<T>>;


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

	string s;
	cin >> s;
	int n = stoi(s);

	int tmp = 0;
	rep(i, s.size()) {
		char c = '0';
		tmp += s[i] - c;
	}

	if (n % tmp == 0) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}

	return 0;
}



Measured memory_bytes: 256
#include <iostream>
#include <stdio.h>
#include <queue>
#include <vector>
using namespace std;
struct node
{
    int to;
    int w;
};
vector<node>ve[100001];
queue<int>que;
int flag[100001];
int re[100001];
int main()
{
    int n;
    cin>>n;
    for(int i=1; i<n; i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        node no;
        no.to=v;
        no.w=w;
        ve[u].push_back(no);
        no.to=u;
        ve[v].push_back(no);
    }
    que.push(1);
    flag[1]=1;
    while(!que.empty())
    {
        int k=que.front();
     //   printf("k=%d\n",k);
        que.pop();
        for(int i=0; i<ve[k].size(); i++)
        {

            node no=ve[k][i];
            if(flag[no.to]==1)
                continue;
            if(no.w%2==1)
            {
                if(re[k]==0)
                    re[no.to]=1;
                else
                    re[no.to]=0;

            }
            else
            {
                if(re[k]==0)
                    re[no.to]=0;
                else
                    re[no.to]=1;
            }
            que.push(no.to);
            flag[no.to]=1;
        }
    }
    for(int i=1; i<=n; i++)
        printf("%d\n",re[i]);
    return 0;
}


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

int main() {
  int n,m,h,a,b;
  cin>>n>>m;
  vector<vector<int>> H(n);
  for (int i = 0; i < n; ++i) {
    cin>>h;
    H[i]=vector<int>(1,h);
  }
  for (int i = 0; i < m; ++i) {
    cin>>a>>b;
    H[--a].push_back(--b);
    H[b].push_back(a);
  }
  int cnt = 0;
  for (int i = 0; i < n; ++i) {
    int h = H[i][0];
    for (int j = 1; j < H[i].size(); ++j) {
      if (H[H[i][j]][0]<h) continue;
      cnt++;
      break;
    }
  }
  cout<<n-cnt<<endl;
}


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

int main() {
  int N;
  cin >> N;
  vector<int> A(N), B(N), C(N);
  for (int i = 0; i < N; i++) {
    cin >> A.at(i) >> B.at(i) >> C.at(i);
  }
  
  vector<int> MVA(N), MVB(N), MVC(N);
  MVA.at(0) = A.at(0);
  MVB.at(0) = B.at(0);
  MVC.at(0) = C.at(0);
  for (int i = 1; i < N; i++) {
    MVA.at(i) = max(MVB.at(i - 1), MVC.at(i - 1)) + A.at(i);
    MVB.at(i) = max(MVC.at(i - 1), MVA.at(i - 1)) + B.at(i);
    MVC.at(i) = max(MVA.at(i - 1), MVB.at(i - 1)) + C.at(i);
  }
  
  cout << max({MVA.at(N - 1), MVB.at(N - 1), MVC.at(N - 1)}) << endl;
}

Measured memory_bytes: 2560
#include<bits/stdc++.h>
using namespace std;
int main(){
  int n,x;
  cin >> n >> x;
  int s[n];
  int i,count=1;
  for(i=0;i<n;i++){
	cin >> s[i];
  }
  int d[n+1];
  d[0]=0;
  for(i=0;i<n;i++){
    d[i+1]=d[i]+s[i];
    if(x<d[i+1]){
      break;
    }
    count++;
  }
  cout << count;
}
    
  

Measured memory_bytes: 256
"use strict";
function Main(input) {
    let cin = new Inputer(input);
    let N = cin.getInt();
    let A = new Array(N + 2);
    A[0] = 0, A[N + 1] = 0;
    for (let n = 1; n <= N; n++) A[n] = cin.getInt();
    let sum = 0;
    for (let n = 0; n <= N; n++) sum += Math.abs(A[n] - A[n + 1]);
    for (let n = 1; n <= N; n++) {
        let ans = sum;
        ans += (Math.abs(A[n - 1] - A[n + 1]) - Math.abs(A[n] - A[n + 1]) - Math.abs(A[n] - A[n - 1]));
        console.log(ans);
    }
}
class Inputer{constructor(t){if(typeof t=='undefined')throw new Error('引数（stdin）を省略できません！');this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){if(typeof t=='undefined')throw new Error('引数（1以上）を省略できません！');let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Measured memory_bytes: 32740
#include <bits/stdc++.h>
using namespace std;
using i64 = int64_t;
using vi = vector<i64>;
using vvi = vector<vi>;

int main() {
    int n;
    cin >> n;
    vvi dp(n + 1, vi(3));
    for (int i = 1; i <= n; i++) {
        vi as(3);
        for (int j = 0; j < 3; j++) {
            cin >> as[j];
        }

        for (int j = 0; j < 3; j++) {
            for (int k = 0; k < 3; k++) {
                if (j == k) continue;
                dp[i][k] = max(dp[i][k], dp[i - 1][j] + as[k]);
            }
        }
    }

    cout << max({dp[n][0], dp[n][1], dp[n][2]}) << endl;
}

Measured memory_bytes: 5760
#include <bits/stdc++.h>
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define pr(...) cerr<< GET_MACRO(__VA_ARGS__,pr6,pr5,pr4,pr3,pr2,pr1)(__VA_ARGS__) <<endl
#define pr1(a) (#a)<<"="<<(a)<<" "
#define pr2(a,b) pr1(a)<<pr1(b)
#define pr3(a,b,c) pr1(a)<<pr2(b,c)
#define pr4(a,b,c,d) pr1(a)<<pr3(b,c,d)
#define pr5(a,b,c,d,e) pr1(a)<<pr4(b,c,d,e)
#define pr6(a,b,c,d,e,f) pr1(a)<<pr5(b,c,d,e,f)
#define pr7(a,b,c,d,e,f,g) pr1(a)<<pr6(b,c,d,e,f,g)
#define pr8(a,b,c,d,e,f,g,h) pr1(a)<<pr7(b,c,d,e,f,g,h)
using namespace std;
using Int = long long;
using ll = long long;
using Double = long double;
const Int INF = (1LL<<55)+1e9; // ~ 3.6 * 1e16
const Int mod = (1e9)+7;
const Double EPS = 1e-8;
const Double PI = 6.0 * asin((Double)0.5);
using P = pair<Int,Int>;
using T = tuple<Int,Int,Int>;
template<class T> T Max(T &a,T b){return a=max(a,b);}
template<class T> T Min(T &a,T b){return a=min(a,b);}
ostream& operator<<(ostream& o,P p){return o<<"("<<p.first<<","<<p.second<<")";}
ostream& operator<<(ostream& o,T t){return o<<"("<<get<0>(t)<<","<<get<1>(t)<<","<<get<2>(t)<<")";}
istream& operator>>(istream& i,P &p){return i>>p.first>>p.second;}
ostream& operator<<(ostream& o,vector<auto> &a){Int i=0;for(auto t:a)o<<(i++?" ":"")<<t;return o;}
istream& operator>>(istream& i,vector<auto> &a){for(auto &t:a)i>>t;return i;}
void prArr(auto a,string s=" "){Int i=0;for(auto t:a)cout<<(i++?s:"")<<t;cout<<endl;}

class CumulativeSum{
public:
  vector<Int> sum;
  CumulativeSum(){}
  CumulativeSum(vector<Int> A){
    Int n = A.size();
    sum.resize(n+1,0);
    for(Int i=1;i<=n;i++) sum[i] += sum[i-1] + A[i-1];
  }
  Int get(Int l,Int r){assert(l<=r && l>=0 && r<=(Int)sum.size());return sum[r] - sum[l];} //[l,r)
};


signed main(){
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  Int n;
  cin>>n;
  vector<Int> A(n);
  cin>>A;
  CumulativeSum Sum(A);
  
  auto get=[&](Int l,Int r){
    Int L = l, R = r;
    while(L+1<R){
      Int M = (L+R)/2;
      Int a = Sum.get(l, M);
      Int b = Sum.get(M, r);
      if(a <= b) L = M;
      else R = M;
    }
    return L;
  };

  auto calc=[](Int a,Int b,Int c,Int d){return max({a,b,c,d}) - min({a,b,c,d});};

  Int ans = INF;
  auto calc2=[&](Int i,Int a,Int c){
    if(!(0 <= a && a <= i && i <= c && c <= n) ) return;
    Int A = Sum.get(0, a);
    Int B = Sum.get(a, i);
    Int C = Sum.get(i, c);
    Int D = Sum.get(c, n);
    if(A && B && C && D) Min(ans, calc(A,B,C,D));
  };
  
  for(Int i=2;i<n-1;i++){
    Int a = get(0, i);
    Int c = get(i, n);
    for(int j = -1;j<=1;j++)
      for(int k=-1;k<=1;k++) calc2(i, a - j,c - k);
  }
  cout<<ans<<endl;
  return 0;
}


Measured memory_bytes: 4992
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <map>
#include <string>

using namespace std;

void solve();

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    solve();
}

void solve() {
    int n,m;
    cin >> n >> m;
    int a[n];
    for(int i = 0; i < n; i++) {
        cin >> a[i];
    }
    int sum = 0;
    for(int i = 0; ; i++) {
        int ma = a[i % n];
        int mi = a[i % n];
        for(int j = 0; j < m; j++) {
            ma = max(ma,a[(i + j) % n]);
            mi = min(mi,a[(i + j) % n]);
        }
        i += m - 1;
        sum += ma - mi;
        if(i % n == n-1) break;
    }
    cout << sum << endl;

    
}

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

int main() {
    int n;
    cin >> n;
    vector<pair<int, int>> v;
    for(int i = 1; i <= n; ++i) {
        for(int j = i+1; j <= n; ++j) {
            if(n&1) {
                if(j != (n-i)) v.push_back(make_pair(i, j));
            } else {
                if(j != (n-i+1)) v.push_back(make_pair(i, j));
            }
        }
    }

    cout << v.size() << '\n';
    for(int i = 0; i < v.size(); ++i) {
        cout << v[i].first << " " << v[i].second << '\n';
    }

    return 0;
}


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

using namespace std;
#define rep(i,m,n) for(int i=m;i<n;++i)
#define llrep(i,m,n) for(ll i=m;i<n;++i)
#define inf 1000000000
#define llinf 1000000000000000000
#define mod 1000000007
#define ll long long
#define ull unsigned long long
#define mp make_pair
#define all(v) v.begin(),v.end()

vector<vector<char>>grid(22, vector<char>(22, '#'));

int dist(int h, int w) {
	vector<vector<int>>hoge(22, vector<int>(22, 999999));
	hoge[h + 1][w + 1] = 0;
	pair<int, int>now = mp(h + 1, w + 1);
	queue<pair<int, int>>q;
	q.push(now);
	while (!q.empty()) {
		now = q.front();
		q.pop();
		if (grid[now.first + 1][now.second] == '.' && hoge[now.first + 1][now.second] > hoge[now.first][now.second] + 1) {
			hoge[now.first + 1][now.second] = hoge[now.first][now.second] + 1;
			q.push(mp(now.first + 1, now.second));
		}
		if (grid[now.first - 1][now.second] == '.' && hoge[now.first - 1][now.second] > hoge[now.first][now.second] + 1) {
			hoge[now.first - 1][now.second] = hoge[now.first][now.second] + 1;
			q.push(mp(now.first - 1, now.second));
		}
		if (grid[now.first][now.second + 1] == '.' && hoge[now.first][now.second + 1] > hoge[now.first][now.second] + 1) {
			hoge[now.first][now.second + 1] = hoge[now.first][now.second] + 1;
			q.push(mp(now.first, now.second + 1));
		}
		if (grid[now.first][now.second - 1] == '.' && hoge[now.first][now.second - 1] > hoge[now.first][now.second] + 1) {
			hoge[now.first][now.second - 1] = hoge[now.first][now.second] + 1;
			q.push(mp(now.first, now.second - 1));
		}
	}
	int ans = 0;
	rep(i, 1, 21) {
		rep(j, 1, 21) {
			if (hoge[i][j] != 999999) {
				ans = max(ans, hoge[i][j]);
			}
		}
	}
	return ans;
}

int main() {
	int h, w;
	cin >> h >> w;
	rep(i, 0, h) {
		rep(j, 0, w) {
			cin >> grid[i + 1][j + 1];
		}
	}
	int ans = 0;
	rep(i, 0, 20) {
		rep(j, 0, 20) {
			if (grid[i + 1][j + 1] == '.') {
				ans = max(ans, dist(i, j));
			}
		}
	}
	cout << ans << endl;
	return 0;
}

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

const int MAX_N = int(6e3) + 10;

int n, mod;
int dp[MAX_N][MAX_N << 1];

int add(int x, int y) {
	assert(x < mod && x >= 0);
	assert(y < mod && y >= 0);
	return x + y >= mod ? x + y - mod : x + y;
}

int sub(int x, int y) {
	assert(x < mod && x >= 0);
	assert(y < mod && y >= 0);
	return x - y < 0 ? x - y + mod : x - y;
}

int mul(int x, int y) {
	assert(x < mod && x >= 0);
	assert(y < mod && y >= 0);
	return 1LL * x * y % mod;
}

int main() {
	scanf("%d%d", &n, &mod);
	int base = n * 3;
	dp[0][base] = 1;
	for (int i = 1; i <= base; ++i) {
		for (int j = -base; j <= base; ++j) {
			if (j > -base)
				dp[i][j + base] = add(dp[i][j + base], dp[i - 1][j - 1 + base]);
			if (j < base && i >= 2)
				dp[i][j + base] = add(dp[i][j + base], mul(i - 1, dp[i - 2][j + base + 1]));
			if (i >= 3)
				dp[i][j + base] = add(dp[i][j + base], mul(i - 1, mul(i - 2, dp[i - 3][j + base])));
		}
	}
	int ans = 0;
	for (int i = 0; i <= base; ++i) {
		ans = add(ans, dp[base][i + base]);
	}
	printf("%d\n", ans);
}

Measured memory_bytes: 285488
import itertools
N, M, Q = map(int,input().split())
L = []
for _ in range(Q):
    L.append(list(map(int,input().split())))


nums = [k+1 for k in range(M)]
ans = 0
for e in itertools.combinations_with_replacement(nums, N):
    temp = 0
    for f in L:
        a, b, c, d = f[0], f[1], f[2], f[3]
        if e[b-1]-e[a-1] == c:
            temp += d
    ans = max(ans,temp)
print(ans)


Measured memory_bytes: 9204
from sys import stdin, stdout
rl = lambda: stdin.readline()
rll = lambda: stdin.readline().split()
rli = lambda: map(int, stdin.readline().split())

INF, NINF = float('inf'), float('-inf')

def main():
	n, W = rli()
	weight = [0 for _ in range(n)]
	val = [0 for _ in range(n)]
	for i in range(n):
		w, v = rli()
		weight[i], val[i] = w, v
	#dp(i, j) = max val using items 1,...,i at 
	#			weight j

	dp = [[NINF for c in range(W+1)] for r in range(n+1)]
	for r in range(n+1):
		dp[r][0] = 0
	for c in range(W+1):
		dp[0][c] = 0
	for r in range(1, n+1):
		w, v = weight[r-1], val[r-1]
		for c in range(1, W+1):
			if c - w < 0:
				dp[r][c] = max(dp[r][c], dp[r-1][c])
			else:
				dp[r][c] = max(dp[r][c], dp[r-1][c], v + dp[r-1][c-w])
	print(dp[-1][-1])
	stdout.close()

if __name__ == "__main__":
	main()

Measured memory_bytes: 278288
n=int(input())
x=[int(X) for X in input().split()]
y=[int(Y) for Y in input().split()]
p1,p2,p3,p=0,0,0,[]
for i in range(n):
    p1+=abs(x[i]-y[i])
print(f'{p1:.5f}')
for i in range(n):
    p2+=(abs(x[i]-y[i]))**2
print(f'{p2**(1/2):.5f}')
for i in range(n):
    p3+=(abs(x[i]-y[i]))**3
print(f'{p3**(1/3):.5f}')
for i in range(n):
    p.append(abs(x[i]-y[i]))
print(f'{max(p):.5f}')


Measured memory_bytes: 5664
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <stdio.h>
#include <algorithm>
#include <utility>
#include <functional>
#include <map>
#include <set>
#include <queue>
#include <list>
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,a,b) for(int i=int(a);i<int(b);++i)
#define crep(i) for(char i='a';i<='z';i++)
#define psortsecond(A,N) sort(A,A+N,[](const pii &a, const pii &b){return a.second<b.second;});
#define psortfirst(A,N) sort(A,A+N,[](const pii &a, const pii &b){return a.first<b.first;});
#define ALL(x) (x).begin(),(x).end()
int ctoi(const char c){
  if('0' <= c && c <= '9') return (c-'0');
  return -1;
}
using namespace std;
using pii  = pair<int,int>;
long long gcd(long long a, long long b){return (b == 0 ? a : gcd(b, a%b));}
long long lcm(long long a, long long b){return a*b/gcd(a,b);}
typedef long long ll;
#define MOD 1000000007
#define EPS 10e-8

int main(){
    char A[19];
    cin >> A;
    if(A[0]=='S'){
        cout << "Cloudy" << endl;
    }
    if(A[0]=='C'){
        cout << "Rainy" << endl;
    }
    if(A[0]=='R'){
        cout << "Sunny" << endl;
    }
}

Measured memory_bytes: 256
def shinsa(data):
    for i in data:
        if i % 2 == 0:
            if i % 3 == 0 or i % 5 == 0:
                continue
            else:
                return 'DENIED'

    return 'APPROVED'

a = int(input())
data = [int(x) for x in input().split()]

result = shinsa(data)
print(result)



Measured memory_bytes: 3064
#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<b;i++)
#define rrep(i,a,b) for(int i=a;i>=b;i--)
#define fore(i,a) for(auto &i:a)
#define all(x) (x).begin(),(x).end()
//#pragma GCC optimize ("-O3")
using namespace std; void _main(); int main() { cin.tie(0); ios::sync_with_stdio(false); _main(); }
typedef long long ll; const int inf = INT_MAX / 2; const ll infl = 1LL << 60;
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; }
//---------------------------------------------------------------------------------------------------
struct UnionFind {
    vector<int> par; // uf(x,y)->y
    UnionFind() {}
    UnionFind(int NV) { init(NV); }
    void init(int NV) { par.clear(); rep(i, 0, NV) par.push_back(i); }
    void reset() { rep(i, 0, par.size()) par[i] = i; }
    int operator[](int x) { return par[x] == x ? x : par[x] = operator[](par[x]); }
    void operator()(int x, int y) { x = operator[](x); y = operator[](y); if (x != y) par[x] = y; }
};
/*---------------------------------------------------------------------------------------------------
　　　　　　　　　　　 ∧＿∧  
　　　　　 ∧＿∧ 　（´<_｀ ）　 Welcome to My Coding Space!
　　　　 （ ´_ゝ`）　/　 ⌒i     @hamayanhamayan
　　　　／　　　＼　 　  |　|     
　　　 /　　 /￣￣￣￣/　　|  
　 ＿_(__ﾆつ/　    ＿/ .| .|＿＿＿＿  
　 　　　＼/＿＿＿＿/　（u　⊃  
---------------------------------------------------------------------------------------------------*/


int N, X[50], Y[50];
//---------------------------------------------------------------------------------------------------
void _main() {
	cin >> N;
	rep(i, 0, N) cin >> X[i] >> Y[i];

	if (N == 1) {
		cout << 1 << endl;
		return;
	}
	
	int ans = inf;
	rep(a, 0, N) rep(b, a + 1, N) {
		int p = X[a] - X[b];
		int q = Y[a] - Y[b];

		if (p == 0 and q == 0) continue;

		UnionFind uf(N);
		rep(i, 0, N) rep(j, 0, N) if (X[i] + p == X[j] and Y[i] + q == Y[j]) uf(i, j);

		int cst = 0;
		rep(i, 0, N) if (uf[i] == i) cst++;
		chmin(ans, cst);
	}

	cout << ans << endl;
}







Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef pair<int,pii> pip;
typedef vector<pip>vip	;
const double PI=acos(-1);
const double EPS=1e-8;
const int inf=1<<30;
int main(){
	int a,b;
	cin>>a>>b;
	if(a<=0&&0<=b)cout<<"Zero"<<endl;
	else{
		int t=min(b,0)-a+1;		
		if(a>0||t%2==0)cout<<"Positive"<<endl;
		else cout<<"Negative"<<endl;
	}
}







Measured memory_bytes: 256
/*
 * Author : Sadi
 * Thu 09/07/2020
 *  0:01:23.58
 */
#include <iostream>
#include <cstdio>
#include <cmath>
#include <climits>
#include <string>
#include <sstream>
#include <algorithm>
#include <utility>
#include <vector>
#include <deque>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <cassert>

using namespace std;

#define    watch(x); cout << "\n" <<  #x << " is: " << x << "\n";
#define    all(a) (a).begin(), (a).end()
#define    fi first
#define    se second

template<class A, class B>
ostream& operator << (ostream& output, const pair<A, B>& p) {
    output << "(" << p.first << ", " << p.second << ")";
    return output;
}

template<class A>
ostream& operator << (ostream& output, const vector<A>& a) {
    output << "[";
    for(auto it = a.begin(); it != a.end(); ++it) {
        if(it != a.begin()) {
            output << ", ";
        }
        output << *it;
    }
    output << "]";
    return output;
}

using lld = long long;
using pii = pair<int, int>;
using pll = pair<lld, lld>;

//const int inf = 1e9;
//const int mod = 1e9 + 7;
//const double PI = acos(-1.0);
//const int mx = 1e5 + 5;



int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
#ifndef ONLINE_JUDGE
//    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif // ONLINE_JUDGE

    int n;
    cin >> n;
    vector<int> v(n);
    for(int i = 0; i < n; ++i) {
    	cin >> v[i];
    }
    int ans = 0;
    int count = 0;
    for(int i = 0; i < n - 1; ++i) {
    	if(v[i + 1] <= v[i]) {
    		count++;
    		ans = max(ans, count);
    	}
    	else {
    		count = 0;
    	}
    }
    cout << ans << endl;
    return 0;
}


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

#define ll long long
#define sd(x) scanf("%d", &(x))
#define pii pair<int, int>
#define F first
#define S second
#define all(c) ((c).begin()), ((c).end())
#define sz(x) ((int)(x).size())
#define ld long double

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

#ifdef LOCAL
#define cerr cout
#else
#endif

#define TRACE

#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
	cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
	const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

ll get(int H, int W, int K){
	int R = 2 * K - 2;
	ll ret = 0;
	for(int x = 1; x < H; x++){
		for(int p = 1; p * x - 3 * max(H, W) <= R && p < W; p++){
			int b = __gcd(H - x, p);
			int r = R - p * x + b;

			int mx = max(0, r) / (H-x);

			ret += min(mx, W - 1);
			
			for(int q = mx + 1; q < W; q++){
				if(q * (H - x) > r + x + H) break;
				ret += (q * (H - x) - __gcd(q, x) - __gcd(abs(p - q), H)) <= r;
			}
		}
	}
	return ret;
}

int main(){
	int W, H, K; cin >> W >> H >> K;
	cout <<  2 * (get(H, W, K) + get(W, H, K)) << endl;
}

Measured memory_bytes: 3652
#include<algorithm>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<string>
#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (int)n; i++)
#define ll long long 
using namespace std;
int main(){
  int n;
  cin >>n;
  vector<string> vec(n);
  rep(i,n){
    cin >>vec[i];
  }
  set<string> S;
  for(string x:vec){
    S.insert(x);
  } 
  cout <<S.size()<<endl;
}

Measured memory_bytes: 25076
// Original: https://github.com/tanakh/competitive-rs
#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused_imports)]
use std::cmp::{max, min};
#[allow(unused_imports)]
use std::collections::HashMap;

fn main() {
    input!(
        n: usize,
        m: usize,
        q: usize,
        lr: [(usize, usize); m],
        pq: [(usize, usize); q]
    );

    let mut acc = vec![vec![0i64; n + 10]; n + 10];
    for &(l, r) in &lr {
        acc[l][r] += 1;
    }

    for i in 1..n + 1 {
        for j in 1..n + 1 {
            acc[i][j] += acc[i - 1][j] + acc[i][j - 1] - acc[i - 1][j - 1];
        }
    }

    for &(p, q) in &pq {
        let ans = acc[q][q] - acc[p - 1][q] - acc[q][p - 1] + acc[p - 1][p - 1];
        println!("{}", ans);
    }
}


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

using namespace std;

typedef long long ll;

int main() {
    int N;
    vector<ll> L;

    cin >> N;
    for (int i = 0; i < N; i++) {
        ll l;
        cin >> l;
        L.push_back(l);
    }

    int cnt = 0;
    for (int i = 0; i < N - 2; i++) {
        for (int j = i + 1; j < N-1; j++) {
            for (int k = j + 1; k < N; k++) {
                if (L[i] != L[j] && L[i] != L[k] && L[j] != L[k]) {
                    ll m = 0;
                    m = max(max(L[i], L[j]), L[k]);
                    ll rest = L[i] + L[j] + L[k] - m;
                    if (rest > m) {
                        cnt++;
                    }
                }
            }
        }
    }

    cout << cnt << endl;
}

Measured memory_bytes: 3628
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <string>
#include <map>
#include <cstring>
#include <ctime>
#include <vector>
#define inf 1e9
#define ll long long
#define maxn 20010
#define y1 fuck
#define For(i,j,k) for(int i=j;i<=k;i++)
#define Dow(i,j,k) for(int i=k;i>=j;i--)
using namespace std;
inline void read(ll &tx){   ll 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();}  tx=x*f; }
inline void write(ll x){    if (x<0) putchar('-'),x=-x; if (x>=10) write(x/10);   putchar(x%10+'0');  }
inline void writeln(ll x){write(x);puts("");}
ll n,a,b,c,d;
int main()
{
	read(n);read(a);read(b);read(c);read(d);
	ll ne=b-a;
	For(i,0,n-1)
	{
		ll L=c*i,R=d*i;
		L=L-d*(n-i-1);R=R-c*(n-i-1);
		if(ne>=L&&ne<=R)	{puts("YES");return 0;}
	} 
	puts("NO");
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
using P = pair<int, int>;
#define rep(i,n) for(int i=0; i<(n); i++)
#define all(x) (x).begin(),(x).end()
#define MAX(x) *max_element(ALL(x))
#define SIZE(x) ((ll)(x).size())
#define INF 1000000000000

int gcd(int a,int b){return b?gcd(b,a%b):a;}
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};

int main() {
    int a, b, d, r;
    double f;
    cin >> a >> b;
    d = a / b;
    r = a % b;
    f = double(a) / b;
    cout << d << " " << r << " " << fixed << setprecision(6) << f << endl;
}


Measured memory_bytes: 3296
def printer(A):
    ret = str(A[0])
    for i in range(1, len(A)):
        ret += " " + str(A[i])
    print(ret)
    return True


def bubblesort(A):
    ret = 0
    flag = True
    num = len(A)
    while flag is True:
        flag = False
        for i in reversed(range(1, num)):
            if A[i - 1] > A[i]:
                tmp = A[i - 1]
                A[i - 1] = A[i]
                A[i] = tmp
                flag = True
                ret += 1
        # num -= 1
    return ret


n = int(input())
A = list(map(int, input().split()))

ans = bubblesort(A)
# print(A)
printer(A)
print(ans)


Measured memory_bytes: 5600
#!/usr/bin/env python3
import sys
import numpy as np


def solve(N: int, A: "List[int]"):
    emp = [0] * N
    for a in A:
        emp[a-1]+=1

    for e in emp:
        print(e)
    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N - 2 + 1)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()


Measured memory_bytes: 52940
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <queue>

using namespace std;

// int height(unordered_map<int, vector<int>>& um, int target) {
//     int ret = 0;
//     for (int next : um[target]) {
//         for (int m : um[next]) {
//             if (m == target) continue;
//             ret = max(ret, height(um, m));
//         }

//         cout << next << endl;
//         // ret = max(ret, 1 + height(um, next));
//     }
//     return ret;
// }

int main() {
    int n;
    cin >> n;
    unordered_map<int, vector<int>> um;
    for (int i = 0; i < n - 1; ++i) {
        int a, b;
        cin >> a >> b;
        um[a].push_back(b);
        um[b].push_back(a);
    }
    int start;
    for (int i = 0; i < n; ++i) {
        if (um[i + 1].size() > 1) {
            start = i + 1;
            break;
        }
    }

    vector<int> v(n, 0);
    queue<int> q;
    q.push(start);
    int i = 1;
    while (!q.empty()) {
        int target = q.front();
        q.pop();
        v[target - 1] = i++;
        for (int next : um[target]) {
            if (um[next].size() > 1) {
                if (v[next - 1] == 0) q.push(next);
            }
        }
    }
    for (int j = 0; j < n; ++j) {
        if (v[j] == 0) v[j] = i++;
    }

    vector<int> c(n);
    int sum = 0;
    int m = 0;
    for (int i = 0; i < n; ++i) {
        cin >> c[i];
        sum += c[i];
        m = max(m, c[i]);
    }
    sort(c.rbegin(), c.rend());
    cout << sum - m << endl;
    for (int i = 0; i < n; ++i) {
        cout << c[v[i] - 1];
        if (i != n - 1) cout << " ";
    }
    cout << endl;
}


Measured memory_bytes: 1280
#include <iostream>
#include <vector>
using namespace std;
int main(void){
  int n;
  while(cin>>n,n){
  vector<string> s(n);
    for(int i=0;i<n;++i)
      cin>>s[i];
    int max=0;
    for(int i=0;i<n;++i){
      char bf1='1',bf2='1';
      int cnt1=0,cnt2=0;
      for(int j=0;j<n;++j){
        if(s[i][j]=='1'){
          ++cnt1;
          if(max<cnt1)max=cnt1;
        }else cnt1=0;
        if(s[j][i]=='1'){
          ++cnt2;
          if(max<cnt2)max=cnt2;
        }else cnt2=0;
        bf1=s[i][j];
        bf2=s[j][i];
      }
    }
    for(int i=-n+1;i<n;++i){
      char bf='1';
      int cnt=0;
      for(int j=0;j<n;++j){
        if(n<=i+j||i+j<0)continue;
        if(s[i+j][j]=='1'){
          ++cnt;
          if(max<cnt)max=cnt;
        }else cnt=0;
      }
    }
    for(int i=0;i<2*n;++i){
      char bf='1';
      int cnt=0;
      for(int j=0;j<n;++j){
        if(n<=i-j||i-j<0)continue;
        if(s[i-j][j]=='1'){
          ++cnt;
          if(max<cnt)max=cnt;
        }else cnt=0;
      }
    }
    cout<<max<<endl;
  }
  return 0;
}

Measured memory_bytes: 1292
import java.util.*;
class Main
{
    int dx[]={-1,0,1,0};
    int dy[]={0,1,0,-1};
    char[][] map;
    void run()
    {
	Scanner sc=new Scanner(System.in);
	while(true){
	    int W=sc.nextInt();
	    int H=sc.nextInt();sc.nextLine();
	    if(W==0&&H==0)break;
	    
	    int startX=0,startY=0;
	    map=new char[H+2][W+2];
	    for(int i=0;i<H+2;i++){
		Arrays.fill(map[i],'#');
	    }
	    for(int i=1;i<H+1;i++){
		char[] s=sc.next().toCharArray();
		for(int j=0;j<W;j++){	
		    if(s[j]=='@'){
			startY=i;
			startX=j+1;
		    }
		    map[i][j+1]=s[j];	
		}
	    }
	    System.out.println(DFS(startY,startX));
	}
    }
    int DFS(int y,int x)
    {
	if(map[y][x]=='#')return 0;
	map[y][x]='#';
	int sum=1;
	for(int i=0;i<4;i++){
	    sum+=DFS(y+dy[i],x+dx[i]);
	}
	return sum;
    }
    
    public static void main(String[] args)
    {
	new Main().run();
    }
}

Measured memory_bytes: 12000
#include<bits/stdc++.h>
#define forn(i,n) for(int i = 0; i < n; i++)
#define fi first
#define se second
long double A, B;
using namespace std;

int main(){
	cin >> A >> B;
	bool found = false;
	long double n;
	forn(i,10000){
		n = i + 1.0;
		if(floor(n*0.08) == A && floor(n*0.1) == B){
			cout << n << '\n';
			found = true;
			break;
		}
	}
	//cout << n1 << '\n';
	//cout << n2 << '\n';
	if(!found) cout << "-1\n";
	return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
int INF = 1e9+7;
int mod = 1e9+7;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int dp[100005];
vector<vector<int>> ki;
int dfs(int x) {
    if(dp[x] != -1) {
        return dp[x];
    }
    int res = 0;
    for(int i = 0; i < ki[x].size(); i++) {
        res = max(res,dfs(ki[x][i])+1);
    }
    return dp[x] = res;
}
int main() {
    int N,M;
    cin >> N >> M;
    ki.assign(N,vector<int>());
    for(int i = 0; i < M; i++) {
        int x,y;
        cin >> x >> y;
        x--;y--;
        ki[x].push_back(y);
    }
    for(int i = 0; i < N; i++) {
        dp[i] = -1;
    }
    int ans = 0;
    for(int i = 0; i < N; i++) {
        ans = max(ans,dfs(i));
    }
    cout << ans << endl;
}

Measured memory_bytes: 11044
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main()
{
	ll n,k,x=0,t;
	scanf("%lld %lld",&n,&k);
	if(n%k==0)
	{
		printf("0\n");
	}
	else
	{
		if(n>k)
		{
		t=n%k;
		x = k-t;
	}
	else
	{
	t = n%k;
	x = min(t,k-t);
	}
		printf("%lld\n",x);
	}
}

Measured memory_bytes: 256
import sys
input = sys.stdin.readline
#n = int(input())
#l = list(map(int, input().split()))
'''
A=[]
B=[]
for i in range():
    a, b = map(int, input().split())
    A.append(a)
    B.append(b)'''

n=int(input())
a = list(map(int, input().split()))
if (a[0]==1 and n+1>1) or a[0]>1:
    print(-1)
    sys.exit()
if n==0 and a[0]==1:
    print(1)
    sys.exit()

su=[0]*(n+1)
for i in range(1,n+1)[::-1]:
    su[i-1]+=su[i]+a[i]
#print(su)
yo_next=min(2-a[0],su[0])
cnt=yo_next+1

for i in range(1,n):
    if yo_next-a[i]<1:
        print(-1)
        sys.exit()
    
    yo_next=min(su[i],(yo_next-a[i])*2)
    cnt+=yo_next
    #print(cnt,su[i+1],(yo_next-a[i])*2)
if yo_next<a[-1]:
    print(-1)
    sys.exit()
else:
    print(cnt)

Measured memory_bytes: 20512
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> mp;
ll inf =  1e9;
ll M = 10000;

int main(){
while(1){
    ll n;
    cin>>n;
    if(n==0)break;
    vector<ll> hp(n);
    for(ll i=0;i<n;i++)cin>>hp[i];
    vector<mp> da,ds;
    ll m;
    cin>>m;
    bool f = false;
    for(ll i=0;i<m;i++){
	string s;
	cin>>s;
	ll cost,damage;
	cin>>cost>>s>>damage;
	if( s == "All" ){
	    da.push_back( mp( cost , damage ) );
	}else{
	    ds.push_back( mp( cost , damage ) );
	}
	if( cost == 0 && damage != 0 ) f = true;
    }
    if( f ){
	cout<<0<<endl;
	continue;
    }
    ll n1 = da.size(),n2 = ds.size();
    vector<vector<ll> > dpa(n1+1,vector<ll>( M + 1 , 0 ) );//cost に関するdamage maximize
    vector<vector<ll> > dps(n2+1,vector<ll>( M + 1 , 0 ) );
    /*cout<<"all"<<endl;
    for(auto i:da){
	cout<<i.first<<' '<<i.second<<endl;
    }*/
    for(ll i=0;i<n1;i++){
	for(ll j=0;j<=M;j++){
	    if( da[i].first <= j ){
		//cout<<j<<':'<<dpa[i+1][j-da[i].first]<<endl;
		dpa[i+1][j] = max( dpa[i][j] , dpa[i+1][j-da[i].first] + da[i].second );
	//	cout<<dpa[i+1][j]<<endl;
	    }else{
		dpa[i+1][j] = dpa[i][j];
	    }
	}
    }
    for(ll i=0;i<n2;i++){
	for(ll j=0;j<=M;j++){
	    if( ds[i].first <= j ){
		dps[i+1][j] = max( dps[i][j] , dps[i+1][j-ds[i].first] + ds[i].second );
	    }else{
		dps[i+1][j] = dps[i][j];
	    }
	}
    }
    //for(ll i=0;i<100;i++)cout<<i<<' '<<dpa[n][i]<<endl;
    ll res = inf;
    for(ll i=0;i<=M;i++){
    //for(ll i=0;i<=80;i++){
	ll D = dpa[n1][i];
	ll cost = i;
	//cout<<cost<<' '<<D<<endl;
	for(ll j=0;j<n;j++){
	    if( hp[j] - D > 0 ){
		auto it = lower_bound( dps[n2].begin() , dps[n2].end() , hp[j]-D );
		cost += (it-dps[n2].begin() );
	    }
	}
	res = min( cost, res );
    }
    cout<<res<<endl;
}
    return 0;
}



Measured memory_bytes: 10760
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")    
using namespace std;
namespace mp = boost::multiprecision;
// 任意長整数型
using Bint = mp::cpp_int;
// 仮数部が1024ビットの浮動小数点数型(TLEしたら小さくする)
using Real = mp::number<mp::cpp_dec_float<1024>>;
#define lli long long int
#define uli unsigned long long int
#define INF 999999999999
#define rep(i,m,n) for(lli i = m;i < n;i++)
#define rrep(i,m,n) for(lli i=m-1;i>=n;i--)
#define pb(n) push_back(n)
#define UE(N) N.erase(unique(N.begin(),N.end()),N.end());
#define Sort(n) sort(n.begin(), n.end())
#define Rev(n) reverse(n.begin(),n.end())
#define Out(S) cout << S << endl
#define NeOut(S) cout << S
#define HpOut(S) cout << setprecision(50) << S << endl
#define Vec(K,L,N,S) vector<L> K(N,S)
#define DV(K,L,N,M,S) vector<vector<L>> K(N,vector<L>(M,S))
#define TV(K,L,N,M,R,S) vector<vector<vector<L>>> K(N,vector<vector<L>>(M,vector<L>(R,S)))
#define pint pair<lli,lli>
#define paf(L,R) pair<L,R>
#define mod 998244353
#define MAX 10000000
#define ALL(a)  a.begin(),a.end()
#define chmax(a, b) a = (((a)<(b)) ? (b) : (a))
#define chmin(a, b) a = (((a)>(b)) ? (b) : (a))
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  int N;
  cin >> N;
  Vec(A,lli,N,0);
  Vec(B,lli,N,0);
  rep(i,0,N)cin >> A[i] >> B[i];
  Sort(A);Sort(B);
  if(N&1)Out(B[N/2]-A[N/2]+1);
  else Out((B[N/2]+B[N/2-1])-(A[N/2]+A[N/2-1])+1);
}


Measured memory_bytes: 6364
/*
 * wafuIroha.cpp
 *
 *  Created on: 2020/02/23
 *      Author: black
 */
#include <iostream>
using namespace std;

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

	int *a = new int[n];
	for (int i=0; i<n; ++i){
		cin >> a[i];
	}

	int min = 1000;
	int max = 0;

	for(int i=0; i<n; ++i){
		if (a[i] < min){
			min = a[i];
		}
		if (a[i] > max){
			max = a[i];
		}
	}

	cout << max-min << endl;

	return 0;
}



Measured memory_bytes: 256
#include<stdio.h>
#include<stdlib.h>
#define MAX 2000001
#define max 10000

int main(){
  unsigned short *A,*B;
  int C[max+1],i,n,j;

  scanf("%d",&n);
  A=malloc(sizeof(short)*n+1);
  B=malloc(sizeof(short)*n+1);
  for(i=0;i<=max;i++){
    C[i]=0;
  }

  for(i=0;i<n;i++){
    scanf("%hu",&A[i+1]);
    C[A[i+1]]++;
  }
  for(i=1;i<=max;i++){
    C[i]+=C[i-1];
  }
  for(j=1;j<=n;j++){
    B[C[A[j]]]=A[j];
    C[A[j]]--;
  }

  for(i=1;i<=n;i++){
    if(i!=1)printf(" ");
    printf("%d",B[i]);
  }

  printf("\n");

  return 0;
}




Measured memory_bytes: 9624
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int []S = new int[n + 1];
        for(int i = 0; i < n; i++) {
            S[i] = scan.nextInt();
        }
        int q = scan.nextInt();
        int []T = new int[q];
        for(int i = 0; i < q; i++) {
            T[i] = scan.nextInt();
        }
        scan.close();
        int sum = 0;
        for(int i = 0; i < q; i++) {
            if(search(S, n, T[i]) == 1) {
                sum ++;
            }
        }
        System.out.println(sum);
    }
    public static int search(int A[], int n, int key) {
        int i = 0;
        A[n] = key;
        while(A[i] != key) {
            i ++;
        }
        if(i != n) {
            return 1;
        }
        return 0;
    }
}



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

using namespace std;

using ll = long long;

template <typename T = ll>
using vec = vector<T>;

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

    int n;
    cin >> n;

    map<int, int> cnt;
    ll res = 0;
    for (int i = 0; i < n; i++) {
        int a;
        cin >> a;
        res += cnt[i - a];
        cnt[a + i]++;
    }

    cout << res << '\n';
}

Measured memory_bytes: 20504
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

long long lucas(int i){
    if(i==0) return 2;
    else if(i==1) return 1;
    else{
        long long x,y,z;
        x = 2; y = 1;
        for(int j=1;j<i;j++){
            z = x + y;
            x = y;
            y = z;
        }
        return z;
    }
}

int main(){
    int N;
    cin >> N;
    long long ans = lucas(N);
    cout << ans << endl;
}


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

int main(){
    int A, B;
    cin >> A >> B;

    int X = (B+A-1)/A*A;
    int p = X/A;
    int q = X/B + X%B;
    cout << (p < q ? X : -1) << endl;
    return 0;
}



Measured memory_bytes: 3092
fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val a = readLine()!!.split(" ").map { it.toInt() }

    var g = a[0]
    for (i in 1 until n) {
        g = gcd(g, a[i])
    }
    println(g)
}

fun gcd(a: Int, b: Int): Int {
    if (a < b) return gcd(b, a)
    if (b == 0) return a
    return gcd(b, a % b)
}

Measured memory_bytes: 54132