akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#include <boost/integer/common_factor.hpp>
#include <boost/integer/common_factor_rt.hpp>

using std::string;
using std::vector;
using std::map;
using std::pair;
using std::cin;
using std::cout;

typedef uintmax_t    ull;
typedef intmax_t     ll;
typedef uint64_t     ul;
typedef uint32_t     ui;
typedef uint8_t      uc;

template<class T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vc)
{
  for (auto it = vc.begin(); it != vc.end(); ++it)
  {
    if (std::next(it) == vc.end())
      os << *it;
    else
      os << *it << ' ';
  }
  return os;
}

template<class T1, class T2>
inline
std::ostream & operator<<(std::ostream & os, const std::pair<T1, T2> & p)
{
  return os << p.first << ' ' << p.second;
}

void solve(void)
{
  ui N{}, W{}; std::cin >> N >> W;
  vector<ui> w(N), v(N);
  for(ui i = 0; i < N; ++i) cin >> w[i] >> v[i];

  vector<vector<ull>> dp(N, vector<ull>(W + 1));
  for(ui row = 0; row < dp.size(); ++row)
  {
    for(ui column = 1; column < dp[row].size(); ++column)
    {
      if(column < w[row])
      {
        dp[row][column] = row ? dp[row - 1][column] : 0;
      }
      else
      {
        dp[row][column] = row ? std::max(dp[row - 1][column], dp[row - 1][column - w[row]] + v[row]) : v[row];
      }
    }
  }

  auto ans = dp.back().back();
  cout << ans << '\n';
  return;
}

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

  solve();

  return 0;
}


Measured memory_bytes: 79488
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <ctime>
#include <queue>
#include <stack>
#include <functional>
#include <bitset>
#include <assert.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef pair<ll,ll> P;
typedef vector<P> vpl;
typedef tuple<ll,ll,ll> tapu;
#define rep(i,n) for(ll i=0; i<(n); i++)
#define REP(i,a,b) for(int i=(a); i<(b); i++)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
const int inf = 1<<30;
const ll linf = 1LL<<62;
const int MAX = 510000;
ll dy[8] = {0,1,0,-1,1,-1,1,-1};
ll dx[8] = {1,0,-1,0,1,-1,-1,1};
const double pi = acos(-1);
const double eps = 1e-7;
template<typename T1,typename T2> inline bool chmin(T1 &a,T2 b){
	if(a>b){
		a = b; return true;
	}
	else return false;
}
template<typename T1,typename T2> inline bool chmax(T1 &a,T2 b){
	if(a<b){
		a = b; return true;
	}
	else return false;
}
template<typename T> inline void print(T &a){
    rep(i,a.size()) cout << a[i] << " ";
    cout << "\n";
}
template<typename T1,typename T2> inline void print2(T1 a, T2 b){cout << a << " " << b << "\n";}
template<typename T1,typename T2,typename T3> inline void print3(T1 a, T2 b, T3 c){
	cout << a << " " << b << " " << c << "\n";
}
const int mod = 1e9 + 7;
//const int mod = 998244353;

int main(){
	int n; cin >> n;
	vector<int> V(n),W(n);
	rep(i,n) cin >> V[i] >> W[i];
	int M = 1024;
	vector<vector<pair<int,int>>> vp(M);
	vp[0].emplace_back(0,0);
	vp[0].emplace_back(W[0],V[0]);
	REP(i,1,M){
		if(i >= n) break;
		vector<pair<int,int>> vv;
		for(auto b : vp[(i-1)/2]){
			vv.emplace_back(b);
			vv.emplace_back(b.first+W[i], b.second+V[i]);
		}
		sort(all(vv));
		int now = -1;
		for(auto b : vv){
			if(now < b.second){
				vp[i].push_back(b);
				now = b.second;
			}
		}
	}
	int q; cin >> q;
	while(q--){
		int v,L; scanf("%d%d",&v,&L); v--;
		vector<pair<int,int>> acc;
		acc.emplace_back(0,0);
		while(v >= M){
			vector<pair<int,int>> tmp;
			for(auto b : acc){
				tmp.emplace_back(b);
				tmp.emplace_back(b.first+W[v], b.second+V[v]);
			}
			acc = tmp;
			v = (v-1) / 2;
		}
		int ans = 0;
		for(auto b : acc){
			//print2(b.first,b.second);
			/*for(auto c : vp[v]){
				print2(c.first, c.second);
			}*/
			pair<int,int> pp = {L-b.first, inf};
			//print2(pp.first,pp.second);
			auto itr = lower_bound(all(vp[v]), pp);
			if(itr != vp[v].begin()){
				itr--;
				//print2((*itr).second, b.second);
				chmax(ans, (*itr).second + b.second);
			}
		}
		cout << ans << "\n";
	}
}

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

using namespace std;

int main()
{
    int n, l;
    string x;
    vector <string> A;
    cin>>n>>l;
    for(int i=0; i<n; i++)
    {
        cin>>x;
        A.push_back(x);
    }
    sort(A.begin(),A.end());
    for(int i=0; i<n; i++)
    {
        cout<<A[i];
    }
    cout<<endl;
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
  int a[3],ans;
  cin >> a[0] >> a[1] >> a[2];
  sort(a,a+3);
  ans=(a[2]-a[0])/2+(a[2]-a[1])/2;
  a[0]=a[2]-(a[2]-a[0])%2;
  a[1]=a[2]-(a[2]-a[1])%2;
  sort(a,a+3);
  if (a[0]!=a[2]){
    if (a[1]==a[2]) ans+=2;
    else ans++;
  }
  cout << ans << endl;
  return 0;
}

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

int main(){
    int N;  cin >> N;
    vector<int> H(N);
    for(int i=0; i<N; i++) cin >> H[i];
    int M = 0;
    int ans = 0;
    for(int i=0; i<N; i++){
        if(H[i] >= M) ans++;
        M = max(M, H[i]);
    }
    cout << ans << endl;
}

Measured memory_bytes: 256
//#pragma GCC optimize ("Ofast")
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC target("avx,avx2,fma")

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/rope>
#define pb push_back
#define F first
#define S second
#define ins insert
#define mp make_pair
#define fo(i, n1, n, x) for(int i = n1; i <= n; i += x)
#define foo(i, n, n1, x) for(int i = n; i >= n1; i -= x)
#define bit __builtin_popcount
#define md (l + ((r - l) / 2))
#define all(x) x.begin(),x.end()
#define eb emplace_back
#define ub upper_bound
#define lb lower_bound
#define ios ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define file(s) if (fopen(s".in", "r")) freopen(s".in", "r", stdin), freopen(s".out", "w", stdout)

#define endl '\n'

using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;


using ll = long long;
using ull = unsigned long long;

//#define int ll


const int N = 2e5 + 11, mod = 1e9 + 7, mod2 = 998244353;
const int MAX = 1e5 + 11;
const int INF1 = 2e9 + 11;
const ll INF2 = 2e18 + 11;
const double INF3 = 1e8 + 11;
const int base = 500;
const int P2 = 31;
const int dx[] = {1, -1, 0, 0, 1, 1, -1, -1};
const int dy[] = {0, 0, 1, -1, 1, -1, 1, -1};
const double EPS = 1e-6;
const double PI = acos(-1.0);


template<typename T> using ordered_set = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b) { if (a > b) a = b; }
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b) { if (a < b) a = b; }


typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
bool prime(int n) {
    for(int i=2;i<=sqrt(n);i++){
        if(n%i==0){return 0;}
    }return 1;}
ll bp(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}

ll p[N] , sum[N] , dp[N];

void solve() {
    int n;
    cin >> n;
    for(int i = 1; i <= n; i ++) {
        cin >> p[i];
    }
    dp[1] = 1;
    sum[p[1]] = 1;
    for(int i = 2; i <= n; i ++) {
        dp[i] = dp[i-1];
        if(p[i] != p[i-1]) {
            dp[i] += sum[p[i]];
            if(dp[i] > mod)
                dp[i] -= mod;
            sum[p[i]] += dp[i-1];
            if(sum[p[i]] > mod)
                sum[p[i]] -= mod;
        }
    }
    cout << dp[n];
}


signed main() {
    ios;
    int tt = 1;
//    cin >> tt;
    while(tt--) {
        solve();
    }
    return 0;
}
/*

0 0 0
0 0 1
0 1 0

0 1 1
1 0 1
1 0 0
1 1 0
1 1 1

*/


Measured memory_bytes: 4992
n,k = map(int, input().split())
a = list(map(int, input().split()))
gru = [0]*(k+1)
for i in range(1,k+1):
  for x in a:
    if i-x >= 0 and gru[i-x] == 0:
      gru[i] = 1
      break
t = ["Second","First"]
print(t[gru[k]])

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

int main()
{
	int n, a;
	cin >> n;
	int min = 1000000, max = -1000000;
	long sum = 0;
	for (int i = 0; i < n; i++)
	{
		cin >> a;
		if (a < min) min = a;
		if (a > max) max = a;
		sum += a;
	}
	cout << min << " " << max << " " << sum << endl;
	return 0;
}

Measured memory_bytes: 3092
import typing


class DSU:
    '''
    Implement (union by size) + (path compression)
    Reference:
    Zvi Galil and Giuseppe F. Italiano,
    Data structures and algorithms for disjoint set union problems
    '''

    def __init__(self, n: int = 0):
        self._n = n
        self.parent_or_size = [-1] * n

    def merge(self, a: int, b: int) -> int:
        assert 0 <= a < self._n
        assert 0 <= b < self._n

        x = self.leader(a)
        y = self.leader(b)

        if x == y:
            return x

        if -self.parent_or_size[x] < -self.parent_or_size[y]:
            x, y = y, x

        self.parent_or_size[x] += self.parent_or_size[y]
        self.parent_or_size[y] = x

        return x

    def same(self, a: int, b: int) -> bool:
        assert 0 <= a < self._n
        assert 0 <= b < self._n

        return self.leader(a) == self.leader(b)

    def leader(self, a: int) -> int:
        assert 0 <= a < self._n

        if self.parent_or_size[a] < 0:
            return a

        self.parent_or_size[a] = self.leader(self.parent_or_size[a])
        return self.parent_or_size[a]

    def size(self, a: int) -> int:
        assert 0 <= a < self._n

        return -self.parent_or_size[self.leader(a)]

    def groups(self) -> typing.List[typing.List[int]]:
        leader_buf = [self.leader(i) for i in range(self._n)]

        result = [[] for _ in range(self._n)]
        for i in range(self._n):
            result[leader_buf[i]].append(i)

        return list(filter(lambda r: r, result))
      
n,q=map(int,input().split())
dsu=DSU(n)
for i in range(q):
  t,u,v=map(int,input().split())
  if(t==0):
    dsu.merge(u,v)
  else:
    if(dsu.same(u,v)):
      print(1)
    else:
      print(0)

Measured memory_bytes: 88644
#include<bits/stdc++.h>
using namespace std;
int main(){
  int n;cin>>n;
  int k;cin>>k;
  int a[n];
  int m=1000000;
  for(int i=0;i<n;i++){
    cin>>a[i];
    m=min(m,a[i]);
  }
  int dp[k+1];
  fill(dp,dp+k+1,-1);
  for(int i=0;i<m;i++)dp[i]=0;
  for(int i=0;i<k;i++){
    for(int j=0;j<n;j++){
      if(i+a[j]<=k){
        if(dp[i]==0){
          dp[i+a[j]]=1;
        }
        else{
          if(dp[i+a[j]]==-1)dp[i+a[j]]=0;
        }
      }
    }
  }
  if(dp[k]==0)cout<<"Second"<<endl;
  else cout<<"First"<<endl;
}
        
  

Measured memory_bytes: 640
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<queue>
#include<set>
using namespace std;
typedef long long LL;
const int N=310;
int gi() {
	int w=0;bool q=1;char c=getchar();
	while ((c<'0'||c>'9') && c!='-') c=getchar();
	if (c=='-') q=0,c=getchar();
	while (c>='0'&&c <= '9') w=w*10+c-'0',c=getchar();
	return q? w:-w;
}
int f[N][N][N];
int L[N][4],R[N][4];
inline bool check(int r,int i,int j,int k) {
	for (int t=1;t<=3;t++)
		if (R[r][t]) {
			if ((i>=R[r][t])+(j>=R[r][t])+(k>=R[r][t])<t) return false;
			if ((i>=L[r][t])+(j>=L[r][t])+(k>=L[r][t])>t) return false;
		}
	return true;
}
int main()
{
	int n=gi(),m=gi(),i,j,k,t,l,r,x,ans=0;
	const int mod=1e9+7;
	for (i=1;i<=n;i++)
		for (j=1;j<=3;j++) L[i][j]=1<<30,R[i][j]=0;
	while (m--) {
		l=gi(),r=gi(),x=gi();
		if (r==1&&x!=1) return puts("0"),0;
		L[r][x]=min(L[r][x],l);
		R[r][x]=max(R[r][x],l);
	}
	f[1][0][0]=3;
	for (i=1;i<=n;i++)
		for (j=0;j<i;j++)
			for (k=0;k<i;k++)
				if (t=f[i][j][k]) {
					if (check(i+1,i+1,j,k))
						(f[i+1][j][k]+=t)%=mod;
					if (check(i+1,i,i+1,k))
						(f[i+1][i][k]+=t)%=mod;
					if (check(i+1,i,j,i+1))
						(f[i+1][i][j]+=t)%=mod;
				}
	for (j=0;j<n;j++)
		for (k=0;k<n;k++)
			(ans+=f[n][j][k])%=mod;
	printf("%d\n",ans);
	return 0;
}


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

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

    cout << max - min << endl;

}

Measured memory_bytes: 256
#pragma GCC optimize ("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

#include <bits/stdc++.h>
using namespace std;
using Int = long long;
typedef pair<int,int> P; typedef pair<Int,Int> Pl;
const int mod = 1e9+7;
#define END {cout<<ans<<'\n'; return 0;}
#define ALL(v) (v).begin(),(v).end()
#define Pr(type) priority_queue<type>
#define gPr(type) priority_queue<type,vector<type>,greater<type>>
#define V(type) vector<type>
#define rep(i,n) for(int i=0; i<n; i++)
#define rer(i,st,en) for(int i=st; i<en; i++)
#define gnr(i,l,r) for(int i=int(r)-1; i>=int(l); i--)
#define eb emplace_back
#define pri1(a) cout<<(a)<<'\n'
#define pri2(a,n) rep(i,n-1)cout<<a[i]<<' '; cout<<a[n-1]<<'\n'
#define prip(p) cout<<p.first<<' '<<p.second<<'\n'
template<class T> inline bool cmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool cmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int n,m,_,x,y,q;
string s,sb;
bool ok;
char ch;


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

  cin>>n; gPr(int)p;
  rep(i,n){cin>>x; p.push(x);}
  rep(i,n-1){
    x=p.top(); p.pop();
    y=p.top(); p.pop();
    if(-x-y>x+y){x*=-1; y*=-1;}
    else {p.push(x); p.push(y); break;}
    p.push(x); p.push(y);
  }
  Int ans=0;
  rep(i,n){
    x=p.top(); p.pop();
    ans+=x;
  }
  END
}

Measured memory_bytes: 892
# abc148_d.py
from sys import stdin
N = int(stdin.readline().rstrip())
a = [int(x) for x in stdin.readline().rstrip().split()]
#print(a)
cnt = 0
idx = 1
#flg = 1
for i in a:
	if i == idx:
		idx = idx + 1
		#flg = 0
	else:
		cnt = cnt + 1
		#if idx != 1:
			#flg = 1

if cnt == N:
	print(-1)
else:
	print(cnt)



Measured memory_bytes: 25768
#include <iostream>//cout
#include <stdio.h>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <functional>
#include <list>
#include <utility>//swap
using namespace std;
static const int MAX = 200000;
#define rep(i,n) for(int i=0;i<n;i++)
#define GET_ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
 
int main() {
  long long int N, W;
  //long long int x, a, b, c;
  int ans = 0;
  cin >> N;
  int A[2][N];
  int a1 = 0, a2 = 0;
  for (int i = 0; i < 2; i++) {
      for (int j = 0; j < N; j++) {
	cin >> A[i][j];
	if (i)
	  a2 += A[i][j];
      }
  }
  for (int j = 0; j < N; j++) {
    a1 += A[0][j];
    if (ans < a2+a1)
      ans = a2+a1;
    a2 -= A[1][j];
  }
  cout << ans << endl;
}

Measured memory_bytes: 384
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
int sum=0;
int H,W;
int c[10][10];
int main()
{
    ios::sync_with_stdio(false);
    cin>>H>>W;
    for(int i=0; i<10; i++)
        for(int j=0; j<10;j++)
            cin>>c[i][j];

    for(int k=0; k<10; k++)
        for(int i=0; i<10; i++)
            for(int j=0; j<10;j++)
                c[i][j]=min(c[i][j],c[i][k]+c[k][j]);
    ll ans=0;
    int t;
    for(int i=0; i<H; i++)
        for(int j=0; j<W; j++)
        {
            cin>>t;
            if(t>=0) ans+=c[t][1];
        }
    cout<<ans<<endl;
}



Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    while(scanf("%d",&n),n!=0) {
        int sum=0,max_s=0,min_s=1000;
        for(int i=0;i<n;i++) {
            int s;
            scanf("%d",&s);
            max_s=max(max_s,s);
            min_s=min(min_s,s);
            sum+=s;
        }
        printf("%d\n",(sum-max_s-min_s)/(n-2));
    }
}

Measured memory_bytes: 3172
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(n);i++) 
#define all(x) (x).begin(), (x).end()
typedef long long ll;
using namespace std;

int main() {
  string S;
  cin >> S;

  int odd = 0;
  int even = 0;
  
  rep(i,S.length()){
    if(i&1){
      (S[i]&1) ? odd++ : even++;
    } else {
      (S[i]&1) ? even++ : odd++;
    }
  }
  cout << min(even,odd) << endl;
}

Measured memory_bytes: 512
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

#define IOS ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define I insert
#define endl '\n'
#define all(x) x.begin(), x.end()

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
 
using vvll = vector< vector<ll> >;
using vll = vector<ll> ;
using vb = vector<bool> ;
using pll = pair<ll, ll> ;

const ll maxs = 1e6+5;
const ll lmaxs = 20;
ll mod = 1e9+7;
ll oo = 1e15;

void pre(){

    

}
int n;
int p[maxs];
int a[maxs];
int bit[maxs];

void add(ll ind,ll val){
    while(ind<=n){
        bit[ind] += val;
        ind += ind&-ind;
    }
}

int get(int ind){
    ll sum=0;
    while(ind){
        sum += bit[ind];
        ind -= ind&-ind;
    }
    return sum;
}


void solve(){

    int m;
    cin>>n>>m;
    int id=1;
    map<int,int> mp;
    memset(p,-1,sizeof p);
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if(mp.find(a[i]) == mp.end()){
            mp[a[i]] = id++;
        }
    }
    for(int i=1;i<=n;i++){
        a[i] = mp[a[i]];
    }
    // for(ll i=1;i<n+1;i++)   
    //     cout << a[i] << " ";
    // cout << endl;
    pair<pair<int,int>,int> q[m];
    int ANS[m];
    for(int i=0;i<m;i++){
        cin>>q[i].ff.ff>>q[i].ff.ss;
        q[i].ss = i;
    }
    sort(q,q+m,[&](pair<pair<int,int>,int> a,pair<pair<int,int>,int> b)->bool{
        return a.ff.ss < b.ff.ss;
    });
    ll ptr=0;
    for(int i=1;i<=n;i++){
        if(p[a[i]] != -1)
            add(p[a[i]],-1);
        p[a[i]] = i;
        add(i,1);

        while(ptr < m and q[ptr].ff.ss == i){
            int x = q[ptr].ff.ff;
            int ind = q[ptr].ss;
            int res = get(i) - get(x-1);
            ANS[ind] = res;
            ptr++;
        }
    }

    for(int i=0;i<m;i++){
        cout << ANS[i] << endl;
        //printf("%d\n",ANS[i]);
    }




}

int main(){

    IOS;
    pre();
    ll T = 1;
    //cin>>T;
    while(T--){
        solve();   
    }
    return 0;
}

Measured memory_bytes: 42864
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <utility>
#include <tuple>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <cmath>
#include <iomanip>
#include <cassert>
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define ALL(x) (x).begin(), (x).end()
#define SZ(x) (int)(x).size()
using namespace std;
using ll = long long;
constexpr ll INF = 3000000000000000000;

template <typename T> bool chmin(T &a, const T &b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <typename T> bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

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

int main() {
    int n;
    cin >> n;
    vector<int> p(n * n), q(n * n);
    REP(i, n * n) {
        int num;
        cin >> num;
        --num;
        p[i] = num / n;
        q[i] = num % n;
    }
    
    vector<vector<int>> s(n, vector<int>(n, 0));
    REP(i, n) REP(j, n) {
        s[i][j] = min({i, j, n - i - 1, n - j - 1});
    }
    vector<vector<bool>> t(n, vector<bool>(n, false));
    int ans = 0;
    REP(i, n * n) {
        ans += s[p[i]][q[i]];
        t[p[i]][q[i]] = true;
        queue<pair<int, int>> que;
        que.push(pair<int, int>(p[i], q[i]));
        while (!que.empty()) {
            int x = que.front().first;
            int y = que.front().second;
            que.pop();
            REP(j, 4) {
                if (x + dx[j] >= 0 && x + dx[j] < n && y + dy[j] >= 0 && y + dy[j] < n) {
                    if (chmin(s[x + dx[j]][y + dy[j]], s[x][y] + (t[x][y] ? 0 : 1))) {
                        que.push(pair<int, int>(x + dx[j], y + dy[j]));
                    }
                }
            }
        }
    }
    
    cout << ans << "\n";
    return 0;
}


Measured memory_bytes: 6296
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> Option<T> {
    let stdin = stdin();
    let s = stdin
        .bytes()
        .map(|c| c.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect::<String>();
    s.parse::<T>().ok()
}

fn main() {
    let n: usize = read().unwrap();
    let m: usize = read().unwrap();
    if n == m {
        println!("Yes");
    } else {
        println!("No");
    }
}

Measured memory_bytes: 4352
# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


# -------------------------------------------------------------
# main
# -------------------------------------------------------------
N,K = map(int,input().split())
A = list(map(int,input().split()))

A.sort()

ans = N
total = 0

for i in range(N):
    # 後ろ(大きい方) からみていく
    a = A[N-1-i]
    # 合計に加えても K を超えないなら, 最小の部分集合に必要
    if total + a < K:
        total += a
    # そうでない場合, 不要
    else:
        ans = min(ans, N-1-i)

print(ans)

Measured memory_bytes: 3572
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long LL;
typedef long double ld;
typedef vector<ll>VI;
typedef pair<ll,ll>P;
#define VV(T) vector<vector<T>>
#define sz(x) int(x.size())
#define PI 3.1415926535897932384626433832795
#define rep(i, n) for (ll i = 0; i < (ll)n; i++)
#define reprev(i,n) for (ll i=(ll)n-1;i>=0;i--)
#define ALL(a)  (a).begin(),(a).end()
#define rALL(a) (a).rbegin(),(a).rend()
#define c_max(a, b) (((ll)a)>((ll)b)?(a):(b))
#define c_min(a,b) (((ll)a)<((ll)b)?(a):(b))
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; }
#define vmax(v) *max_element(ALL(v))
#define vmin(v) *min_element(ALL(v))
#define $(x) {cout<<#x<<" = " <<(x)<<endl;}
#define fi first
#define se second
#define MAX 100100//5
#define MAX2 200100
#define MAX6 1001001//6
#define MAX7 10010010//7
#define SENTINEL 2000000000//9
#define INF 1<<30
#define INFTY 1LL<<61
#define MAX_INT INT_MAX
#define Endl '\n'
#define CLR(mat) memset(mat, 0, sizeof(mat))
inline ll GCD(ll a,ll b){return b?GCD(b,a%b):a;}//最大公約数
inline ll lcm(ll a,ll b){return a*b/GCD(a,b);}//最小公倍数
template<class T> bool contain(const std::string& s, const T& v) {
   return s.find(v) != std::string::npos;
}
//using Edge=pair<int,ll>;
//using Graph=vector<vector<ll> >;//ll or Edge
const int MOD = 1000000007;
//const int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
// vector型から重複を削除 list.erase(unique(ALL(list)),list.end());
// g++ -o a a.cpp -Wall -lm -std=c++17
//push_back -> emplace_back

int N,M,Q;
VI a,b,c,d;
ll score(const VI &A){
   ll res=0;
   for(int i=0;i<Q;++i)if(A[b[i]]-A[a[i]]==c[i])res+=d[i];
   return res;
}
ll dfs(VI &A){
   if(sz(A)==N){
      return score(A);
   }
   ll res=0;
   int prev_last=(A.empty()?0:A.back());//ここ
   for(int add=prev_last;add<M;add++){
      A.emplace_back(add);
      res=max(res,dfs(A));
      A.pop_back();
   }
   return res;
}

int main(){
   cin>>N>>M>>Q;
   a.resize(Q);b.resize(Q);c.resize(Q);d.resize(Q);
   for(int q=0;q<Q;++q){
      cin>>a[q]>>b[q]>>c[q]>>d[q];
      --a[q],--b[q];
   }
   VI A;
   cout<<dfs(A)<<endl;
}

Measured memory_bytes: 3632
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long a = IntStream.range(0, n).map(e -> sc.nextInt()).boxed().distinct().count();
        if (a == n) {
            System.out.println("YES");
        } else {
            System.out.println("NO");
        }
        sc.close();
    }
}

Measured memory_bytes: 101272
import sys
from collections import deque
import bisect
import copy
import heapq
import itertools
import math
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


def main():
    N, K = read_values()
    A = read_list()

    D = {}
    L = []

    l = 1
    r = max(A) + 1

    while l != r:
        m = (l + r) // 2 
        k = 0

        for a in A:
            k += (a - 1) // m 
        if k > K:
            l = m + 1
        else:
            r = m

    print(r)


if __name__ == "__main__":
    main()


Measured memory_bytes: 93020
using System;

namespace Prob0005
{
    class Program
    {
        static void Main(string[] args)
        {
            string line;
            while((line = Console.ReadLine()) != null)
            {
                string[] tokens = line.Split(' ');
                int a = int.Parse(tokens[0]);
                int b = int.Parse(tokens[1]);

                // 例外処理： どちらかが0の場合
                if(a == 0 || b == 0)
                {
                    Console.WriteLine("0 0");
                    continue;
                }

                int gcd = calcGCD(a, b);
                // LCM = a * b / GCD
                // ただし、(a * b)の時点でint型の最大値を
                // 超える懸念があるので計算順は a / GCD * b とする
                Console.WriteLine("{0} {1}", gcd, a / gcd * b);
            }
        }

        // Euclidean Algorithm
        static int calcGCD(int a, int b)
        {
                int tmp;
                if(a < b)
                {
                    tmp = a;
                    a = b;
                    b = tmp;
                }

                while(a % b != 0)
                {
                    tmp = a % b;
                    a = b;
                    b = tmp;
                }

                return b;
        }
    }
}



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

int main(){
  string s;
  cin >> s;
  if(s[1]==s[2] && (s[1]==s[0] || s[2]==s[3])){
    cout << "Yes" << endl;
  }else{
    cout << "No" << endl;
  }
}


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

/*BigInteger
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
namespace xxx = boost::multiprecision;
using Bint = xxx::cpp_int;
using Real = xxx::number<xxx::cpp_dec_float<1024>>;
*/

#define int long long
#define pb(x) push_back(x)
#define m0(x) memset((x), 0LL, sizeof(x))
#define mm(x) memset((x), -1LL, sizeof(x))

//container
#define ALL(x) (x).begin(), (x).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define EACH(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); ++i)
#define EXIsecondT(s, e) ((s).find(e) != (s).end())
#define UNIQUE(v) (v).erase(unique((v).begin(), (v).end()), (v).end());
#define PERM(c) \
  sort(ALL(c)); \
  for (bool c##p = 1; c##p; c##p = next_permutation(ALL(c)))

// debug
#define GET_VAR_NAME(variable) #variable
#define test(x) cout << GET_VAR_NAME(x) << " = " << x << endl;

// bit_macro
#define Bit(n) (1LL << (n))
#define Bitset(a, b) (a) |= (1LL << (b))
#define Bitunset(a, b) (a) &= ~(1LL << (b))
#define Bitcheck(a, b) ((((a) >> (b)) & 1LL) == 1LL)
#define Bitcount(a) __builtin_popcountint((a))

//typedef
typedef long long lint;
typedef unsigned long long ull;
typedef complex<long double> Complex;
typedef pair<int, int> P;
typedef tuple<int, int, int> TP;
typedef vector<int> vec;
typedef vector<vec> mat;

//constant
constexpr int INF = (int)1e18;
constexpr int MOD = (int)1e9 + 7;
constexpr double PI = (double)acos(-1);
constexpr double EPsecond = (double)1e-10;
constexpr int dx[] = {-1, 0, 0, 1, 0, -1, -1, 1, 1};
constexpr int dy[] = {0, -1, 1, 0, 0, 1, -1, 1, -1};

//
template <typename T>
void chmax(T &a, T b) { a = max(a, b); }
template <typename T>
void chmin(T &a, T b) { a = min(a, b); }
//
inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T>
inline string tosecondtring(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}

//
struct Accelerate_Cin {
  Accelerate_Cin() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    cout << fixed << setprecision(20);
  };
} Accelerate_Cin;

signed main() {
  int n, m;
  cin >> n >> m;
  vector<P> cnt(100010);
  vector<int> pint(100010);
  for (int i = 0; i < n; i++) {
    int num;
    cin >> num;
    pint[num]++;
  }

  for (int i = 0; i < 100010; i++) {
    if (pint[i] > 0) {
      cnt[i % m].first += pint[i];
      cnt[i % m].second += pint[i] / 2;
    }
  }
  int ans = 0;
  ans += cnt[0].first / 2;
  for (int i = 1; i <= m / 2; i++) {

    if (i == m - i) {
      ans += cnt[i].first / 2;
    } else {
      ans += min(cnt[i].first, cnt[m - i].first);
      if (cnt[i].first > cnt[m - i].first) {
        ans += min(cnt[i].second, (cnt[i].first - cnt[m - i].first) / 2);
      } else {
        ans += min(cnt[m - i].second, (cnt[m - i].first - cnt[i].first) / 2);
      }
    }
  }
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 2560
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <stack>
#include <vector>
#include <set>
#include <tuple>
#include <utility>
#include <functional>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
typedef tuple<int,int,int> T;
const int INF = 1000000000;
const int MOD = 1000000007;
int main(){
	int n;
	cin >> n;
	vector<int> a(n);
	for(int i = 0;i < n;i++){
		cin >> a[i];
		a[i] -= i+1;
	}

	sort(a.begin(),a.end());

	int b = a[n/2];
	ll ans = 0;
	for(int i = 0;i < n;i++){
		ans += abs(a[i] - b);
	}

	cout << ans << endl;
}



Measured memory_bytes: 1024
'use strict'
function main(inp) {
  inp = inp.trim().split('\n')
  const N = Number(inp[0])
  inp = inp[1].split(' ')
  let ans = ''
  for (let i = 0; i < N; i++) {
    ans += inp[0][i] + inp[1][i]
  }
  console.log(ans)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


Measured memory_bytes: 21064
fn main() {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    let n = buf.trim().parse::<i64>().unwrap();
    buf.clear();
    std::io::stdin().read_line(&mut buf).unwrap();
    let arr = buf.split_whitespace().map(|x| x.parse::<i64>().unwrap());
    let mut cnt: Vec<i64> = std::iter::repeat(0).take(n as usize).collect();
    for a in arr {
        cnt[(a - 1) as usize] += 1;
    }
    for c in cnt {
        println!("{}", c);
    }
}


Measured memory_bytes: 4776
h,w=map(int,input().split())
s=[]
for _ in range(h):
    a = input() 
    if "#" in a:
        s.append(a)
d = []
for i in zip(*s):
    if "#" in i:
        d.append(i)
for j in zip(*d):
    print(*j,sep="")

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

using namespace std;

#define reg register
#define ge getchar()
#define Re read()
#define ll long long
#define MAXN 100100

inline int read() {
	reg int x = 0, t = 0, ch;
	while(!isdigit(ch = ge)) t |= ch == '-';
	while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = ge;
	return t ? -x : x;
}

int a[MAXN + 1];
int b[MAXN + 1];
int cut[MAXN + 1];

int main() {
	int n = Re;
	ll sum = 0;
	ll nd = 0;
	int res = 0;
	for(reg int i = 1; i <= n; i++) {
		a[i] = Re;
		sum += a[i];
	}
	for(reg int i = 1; i <= n; i++) {
		b[i] = Re;
		sum -= b[i];
		cut[i] = a[i] - b[i];
		nd += cut[i] < 0 ? cut[i] : 0;
		res += cut[i] < 0;
	}
	if(sum < 0) puts("-1");
	else {
		sort(cut + 1, cut + 1 + n);
		for(reg int i = n; i >= 0; i--) {
			if(nd >= 0) {printf("%d\n", n - i + res); return 0;}
			nd += cut[i];
		}
	}
	return 0;
}

Measured memory_bytes: 1408
import math
n=int(input())

xy=[map(int,input().split()) for i in range(n)]
x,y=[list(i) for i in zip(*xy)]

sum=0
for i in range(n):
  for j in range(n):
    sum+=math.sqrt((x[i]-x[j])**2+(y[i]-y[j])**2)

#ダブリ p=math.factorial(n-1)*2
ave=sum/n
print(float(ave))
  


Measured memory_bytes: 38384
/*input
10
3 3 3 3 4 4 4 5 5 5

*/
#include <bits/stdc++.h>
#define ll long long int
#define lld long double
using namespace std;
int main(){
	ios::sync_with_stdio(false);
	int n;cin>>n;
	vector<int> vec;
	for(int i=0;i<n;i++){
		int x;cin>>x;
		vec.push_back(x);
	}
	sort(vec.begin(),vec.end());
	ll ar=1;ll mark=0;
	for(int i=n-1;i>=0;){
		if(mark==2){
			break;
		}
		if(vec[i]==vec[i-1]){
			mark++;
			ar*=vec[i];
			i-=2;
		}
		else{
			i--;
		}
	}
	if(mark==2){
		cout<<ar<<endl;
	}
	else{
		cout<<0<<endl;
	}
	return 0;
}

Measured memory_bytes: 892
#include<stdio.h>

int main(){
	int x,y,r;
	scanf("%d %d",&x,&y);
	
	while(1)
	{
		r=x%y;
		if(r==0)break;
		x=y;
		y=r;
	}
	printf("%d",y);
	printf("\n");
	
	return 0;
}
		

Measured memory_bytes: 596
import sys
import collections
import copy
import math
from operator import itemgetter
def input(): return sys.stdin.readline().strip()
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    # divisors.sort()
    return divisors
a = int(input())
ans = 0
for i in range(4):
    if a%10 == 2:
        ans += 1
    a = a//10
print(ans)


Measured memory_bytes: 38512
#include <cstdio>
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cstring>
#include <stack>
#define INT long long
#define oo 99999987654321LL
using namespace std;

stack<char> st;
string s;
int n, a[110], b[110], cnt[110], c;

int main()
{
    cin>>n;
    for(int i = 0 ; i < n ; i++ )
        cin>>a[i];
    sort(a, a+n);
    for(int i = a[n-1] ; i >= a[0] ; i-- )
        b[c++] = i;
    for(int i = (a[n-1]&1?a[0]:a[0]+1) ; i <= a[n-1] ; i++ )
        b[c++] = i;
    for(int i = 0 ; i < n ; i++ )
    {
        int cc = 110, cci, flag = 0;
        for(int j = 0 ; j < c ; j++ )
        {
            if( a[i] == b[j] && cnt[j] < cc )
            {
                cc = cnt[j];
                cci = j;
                flag++;
            }
        }
        if( !flag )
        {
            puts("Impossible");
            return 0;
        }
        cnt[cci]++;
    }
    for(int i = 0 ; i < c ; i++ )
    {
        if( b[i] == a[0] && cnt[i] != 1 )
        {
            puts("Impossible");
            return 0;
        }
    }
    for(int i = 0 ; i < c ; i++ )
        if( cnt[i] == 0 )
        {
            puts("Impossible");
            return 0;
        }
    int flag = 0;
    for(int i = 0 ; i < c ; i++ )
        if( cnt[i] == 1 ) flag = 1;
    if( !flag )
    {
        puts("Impossible");
        return 0;
    }
    puts("Possible");
    return 0;
}


Measured memory_bytes: 256
import sys
input=sys.stdin.readline

def main():
    N = int(input())
    A = [0]*N
    B = [0]*N
    for i in range(N):
        A[i],B[i] = map(int,input().split())
    ans = 0
    for i in range(N-1,-1,-1):
        x = A[i] + ans
        if x%B[i] != 0:
            r = B[i] - x%B[i]
            ans += r
    print(ans)

if __name__ == '__main__':
    main()


Measured memory_bytes: 10868
n=int(input())
xy=[[] for i in range(n)]
for i in range(n):
    a=int(input())
    for j in range(a):
        p,q=[int(k) for k in input().split()]
        xy[i].append([p-1,q])
ans=0
for i in range(2**n):
    s=bin(i)[2:].rjust(n,'0')
    r,t=0,0
    for j in range(n):
        if s[j]=="1":
            p,q=0,0
            for x,y in xy[j]:
                p+=1
                if s[x]!=str(y):
                    break
                q+=1
            if p!=q:
                break
            else:
                r+=1
        else:
            r+=1
        t+=1
    if r==n:
        ans=max(ans,s.count("1"))
        
            
print(ans)


Measured memory_bytes: 3064
# -*- coding:utf-8 -*-

def solve():
    N, K = list(map(int, input().split()))

    # K|a+b K|b+c K|c+a
    # K|2a  K|2b  K|2c

    # Kが奇数のとき、 K|a も K|b も K|c も、Kの倍数
    # Kが偶数のとき、 K/2|a  K/2|b  K/2|c
    if K%2 != 0:
        # Kが奇数のとき、aがKで割り切れる数は、
        kinds = (N//K)  # kinds通りある
        # 同様に、b, cも kinds通りある。
        # よって、答えはa, b, cの組み合わせなので
        print(kinds**3)
        return
    K //= 2
    m = N // K
    ans = (m//2) ** 3 + (m - m//2) ** 3
    print(ans)
    return           


if __name__ == "__main__":
    solve()

Measured memory_bytes: 3060
#include <stdio.h>
#include <math.h>
double fun(double x1,double y1,double x2,double y2,double x3,double y3);
//三角形ABC + 三角形DBC = 三角形ABD + 三角形BCDのときYES
int main(void)
{
	double xa,ya,xb,yb,xc,yc,xd,yd;
	double ABC,ADC,ABD,BCD;
	while(scanf("%lf,%lf,%lf,%lf,%lf,%lf,%lf,%lf",&xa,&ya,&xb,&yb,&xc,&yc,&xd,&yd)!=EOF){
		ABC=fun(xa,ya,xb,yb,xc,yc);
		ADC=fun(xa,ya,xd,yd,xc,yc);
		ABD=fun(xa,ya,xb,yb,xd,yd);
		BCD=fun(xb,yb,xc,yc,xd,yd);
		if(fabs(ABC+ADC-(ABD+BCD))<1e-1)	puts("YES");
		else								puts("NO");
	}
	return 0;
}

double fun(double x1,double y1,double x2,double y2,double x3,double y3){
	double S;
	S=fabs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))/2);
	return S;
}

Measured memory_bytes: 608
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;

int main(){
  int n; cin >> n;
  ll a[n+1];
  for(int i=1; i<=n; i++){
    cin >> a[i];
  }

  sort(a+1, a+n+1);

  ll c[n+1]; c[0] = 0;
  for(int i=1; i<=n; i++) c[i] = c[i-1] + a[i];

  int ans = 1;
  for(int i=n-1; i>=1; i--){
    if(2 * c[i] < a[i+1]){
      break;
    }
    ans++;
  }

  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 1920
(* Examples *)
(*
stdin.ReadLine()
printfn "%d"
printfn "%s"
*)

let internal INF = 1 <<< 31

(* Library *)
module Library = 
  (* Queue *)
  type Queue<'T> (capacity : int) =
    let data = Array.create (capacity + 1) Unchecked.defaultof<'T>
    let length = capacity + 1
    let mutable head = 0
    let mutable tail = 0

    member internal this.Add x = (x + 1) % length
    member internal this.Delete x = (x - 1) % length

    member this.isEmpty =
      if head = tail then true else false

    member this.isFull =
      if this.Add tail = head then true else false

    member this.Enqueue x =
      if this.isFull then 
        raise(new System.Exception("Capacity over"))
      else
        data.[tail] <- x
        tail <- this.Add tail
        ()
        
    member this.Peek =
      if this.isEmpty then 
        None
      else
        Some data.[head]

    member this.Dequeue =
      if this.isEmpty then 
        None
      else
        let result = Some data.[head]
        head <- this.Add head
        result

    member this.Clear =
      head <- 0
      tail <- 0
      ()

(* Standard Input *)
let readSplit elementFun=
  stdin.ReadLine().Split()
  |> Array.map elementFun

let read elementFun =
  stdin.ReadLine() |> elementFun

let readMap H =
  [|for i in 1..H -> stdin.ReadLine()|]
  |> Array.map(fun line ->
    line.ToCharArray()
  )
  |> array2D

(* Main *)
open Library

let [|H; W|] = readSplit int

let map = readMap H

let Q = Queue<int * int * int>(10000)


let mutable firstWhite = 0
map
|> Array2D.iter(fun x ->
  if x = '.' then firstWhite <- firstWhite + 1
)

let countMap = Array2D.create H W -1

let rec solve () =
  match Q.Dequeue with
  | Some (x, y, c) ->
    if x < 0 || x >= H || y < 0 || y >= W || map.[x, y] = '#' || countMap.[x, y] <> -1 then 
      solve ()
    else if x = H - 1 && y = W - 1 then
      countMap.[x, y] <- c
    else
      countMap.[x, y] <- c
      Q.Enqueue (x + 1, y, c + 1)
      Q.Enqueue (x, y + 1, c + 1)
      Q.Enqueue (x - 1, y, c + 1)
      Q.Enqueue (x, y - 1, c + 1)
      solve ()
  | _ -> ()

Q.Enqueue (0, 0, 1)
solve ()

let result = countMap.[H - 1, W - 1]

(
if result = -1 then
  -1
else
  firstWhite - result
)
|> printfn "%d"

Measured memory_bytes: 15068
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 1e5 + 5;
const long long inf = 1e14 + 5;
int n,v[maxn];
long long c, ans,x[maxn];
long long dp[2][maxn], m[2][maxn];
int main(){
	scanf("%d %lld",&n, &c);
	for(int i = 0; i < n; i++){
		scanf("%lld %d",&x[i],&v[i]);
	}
	for(int i = 0; i < n; i++) dp[0][i] = dp[1][i] = -inf;
	long long sum = 0;
	for(int i = 0; i < n; i++){
		sum += v[i];
		dp[0][i] = max(dp[0][i - 1], sum - x[i]);
		m[0][i] = sum - 2 * x[i];
	}
	sum = 0;
	for(int i = n - 1; i >= 0; i--){
		sum += v[i];
		dp[1][i] = max(dp[1][i + 1], sum - (c - x[i]));
		m[1][i] = sum - 2 * (c - x[i]);
	}
	ans = max(dp[0][n-1], dp[1][0]);
	for(int i = 0; i < n; i++){
		ans = max(ans, m[0][i] + dp[1][i + 1]);
		ans = max(ans, m[1][n - i] + dp[0][n - i - 1]);
	}
	if(ans != 0)
		printf("%lld\n",ans);
	else
		printf("0\n");
return 0;
}

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

int main() {
  int A, B, K;
  cin >> A >> B >> K;
  vector<int> v;
  for (int i = 1; i <= min(A, B); ++i) {
    if (A % i == 0 && B % i == 0) {
      v.push_back(i);
    }
  }
  cout << v.at((v.size() - 1) - (K - 1)) << endl;
}


Measured memory_bytes: 256
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>

using namespace std;

int main(void) {
	int a=0, b=0;
	while (cin >> a >> b) {
		cout << int(log10(a + b) + 1) << endl;
	}
	return 0;
}

Measured memory_bytes: 3356
#ifndef DEBUG
#    pragma GCC optimize("O3,no-stack-protector")
#    pragma GCC optimize("unroll-loops")

#    if __cplusplus < 201703L
#        pragma GCC target("avx")
#    else
#        pragma GCC target("avx2")
#    endif

#endif

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
#define dump(x) cout << x << endl
typedef int64_t Int;
typedef long double Ld;

using namespace std;
using Graph = vector<vector<Int>>;

const Ld pi = M_PI;
const Int MOD = 999999999999971;
const Int INF = 1LL << 61;

Int Floor(Int a, Int b) {
    return (a - (a % b)) / b;
}

Int Ceil(Int a, Int b) {
    if (a % b == 0) {
        return a / b;
    } else {
        return Floor(a, b) + 1;
    }
}

Int digits(Int n) {
    return (Int)to_string(n).size();
}

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

    Int n, x;
    cin >> n >> x;
    vector<Int> a(n);
    for (Int i = 0; i < n; i++) {
        cin >> a[i];
    }
    sort(a.begin(), a.end());

    Int ans = 0;
    for (Int i = 0; i < n; i++) {
        if (a[i] <= x) {
            x -= a[i];
            ans++;
        } else {
            break;
        }
    }

    if (ans == n) {
        if (0 < x) {
            ans--;
        }
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 3556
from operator import mul
from functools import reduce


def cmb(n,r):
    r = min(n-r,r)
    if r == 0: return 1
    over = reduce(mul, range(n, n - r, -1))
    under = reduce(mul, range(1,r + 1))
    return over // under


N = int(input())
S = [input() for _ in range(N)]

d = {}
for s in S:
    s = "".join(sorted(s))
    if s in d:
        d[s] += 1
    else:
        d[s] = 1
ans = 0
for v in d.values():
    if v > 1:
        ans += cmb(v, 2)
print(ans)

Measured memory_bytes: 25472
#include <bits/stdc++.h>
#define REP(i,n,N) for(int i = n; i < (int) N; i++)
#define p(s)		cout<<(s)<<endl
using namespace std;

int main() {
	int W,H,N;
	cin>>W>>H>>N;
	int wl=0,wr=W,hu=H,hd=0;
	REP(i,0,N){
		int x,y,a;
		cin>>x>>y>>a;
		if(a==1)	wl=max(wl,x);
		else if(a==2) wr=min(wr,x);
		else if(a==3) hd=max(hd,y);
		else hu=min(hu,y);
	}
	int w=wr-wl,h=hu-hd;
	if(w<=0||h<=0) p(0);
	else p(w*h);
	return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define REP(i, a, n) for (int i = (a); i < (int)(n); ++i)
#define REPC(i, a, n) for (int i = (a); i <= (int)(n); ++i)
#define ALL(t) t.begin(), t.end()
#define RALL(t) t.rbegin(), t.rend()
#define MATINIT(type, row, col, init)                                          \
  vector<vector<type>>(row, vector<type>(col, init));
#define Yes(cond) cout << (cond ? "Yes" : "No") << endl;
#define YES(cond) cout << (cond ? "YES" : "NO") << endl;
using namespace std;
using LL = long long;
using ULL = unsigned long long;
template <class T> using VEC = std::vector<T>;
template <class T> using MAT = std::vector<std::vector<T>>;
void DUMP() { cerr << endl; }
template <class Head, class... Tail> void DUMP(Head &&head, Tail &&... tail) {
  cerr << head << ", ";
  DUMP(std::move(tail)...);
}
template <typename T> ostream &operator<<(ostream &os, vector<T> &vec) {
  os << "{";
  for (auto v : vec)
    os << v << ",";
  os << "}";
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, map<T1, T2> &m) {
  os << "{";
  for (auto p : m)
    os << p << ",";
  os << "}";
  return os;
}
template <typename T1, typename T2>
ostream &operator<<(ostream &os, pair<T1, T2> p) {
  os << "[" << p.first << " " << p.second << "]";
  return os;
}

int main() {
  int n;
  cin>>n;
  int cnt=0;
  while(n>0){
    if(n%10==2)++cnt;
    n/=10;
  }
  cout<<cnt<<endl;

  return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<vector>
using namespace std;


int main() {
	int X, Y, Z;
	int K;
	cin >> X >> Y >> Z;
	cin >> K;
	vector<long long> A(X), B(Y), C(Z);

	for (int i = 0; i < X; i++) cin >> A[i];
	for (int i = 0; i < Y; i++) cin >> B[i];
	for (int i = 0; i < Z; i++) cin >> C[i];

	sort(A.begin(), A.end());
	reverse(A.begin(), A.end());
	sort(B.begin(), B.end());
	reverse(B.begin(), B.end());
	sort(C.begin(), C.end());
	reverse(C.begin(), C.end());

	vector<long long> ABC;
	for (int a = 0; a < X; a++)
	{
		for (int b = 0; b < Y; b++)
		{
			//if ((a + 1) * (b + 1) > K) break;

			for (int c = 0; c < Z; c++)
			{
				if ((a + 1) * (b + 1) * (c + 1) > K) break;

				ABC.push_back(A[a] + B[b] + C[c]);
			}
		}
	}


	sort(ABC.begin(), ABC.end());
	reverse(ABC.begin(), ABC.end());

	for (int i = 0; i < K; i++)
	{
		cout << ABC[i] << endl;
	}

}



Measured memory_bytes: 1404
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <list>
#include <stack>
#include <queue>

#define FOR(i, b, e) for(ll i = (ll)(b); i < (ll)(e); ++i)
#define RFOR(i, b, e) for(ll i = (ll)(e-1); i >= (ll)(b); --i)
#define REP(i, n) FOR(i, 0, n)
#define RREP(i, n) RFOR(i, 0, n)
#define REPC(x,c) for(const auto& x:(c))
#define VS vector<string>
#define VL vector<long long>
#define VI vector<int>
#define VVI vector<vector<int>>
#define VVL vector<vector<ll>>
#define ALL(x) (x).begin(),(x).end()
#define SORT(x) sort(ALL(x))
#define RSORT(x) sort((x).rbegin(),(x).rend())
#define PAIR pair<ll,ll>
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() );

using  ll = long long;
constexpr ll MOD = 1000000007;
using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::vector;
using std::list;
using std::map;
using std::unordered_map;
using std::multimap;
using std::set;
using std::unordered_set;
using std::multiset;

ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
ll pow(ll a, ll b) {
	ll ans = 1;
	while (b > 0) {
		if (b % 2 == 1) {
			ans *= a;
			ans %= MOD;
		}
		b /= 2;
		a *= a;
		a %= MOD;
	}
	return ans;
}
ll comb(ll a, ll b) {
	if (a - b < b) { return comb(a, a - b); }
	ll c = 1;
	FOR(i, a - b + 1, a + 1) {
		c *= i;
		c %= MOD;
	}
	ll k = 1;
	FOR(i, 2, b + 1) {
		k *= i;
		k %= MOD;
	}
	c *= pow(k, MOD - 2);
	return c % MOD;
}
multiset<ll> prime_decomposition(ll n) {
	ll i = 2;
	multiset<ll> table{};
	while (i * i <= n) {
		while (n % i == 0) {
			n /= i;
			table.emplace(i);
		}
		++i;
	}
	if (n > 1) {
		table.emplace(n);
		return table;
	}
	return table;
}

int main() {
	int n;
	cin >> n;
	VL v(n + 2);
	v[0] = 0; v[n + 1] = 0;
	REP(i, n) {
		cin >> v[i + 1];
	}

	ll s = 0;
	FOR(i, 1, n + 2) {
		s += abs(v[i] - v[i - 1]);
	}

	FOR(i, 1, n + 1) {
		cout <<
			s -
			abs(v[i - 1] - v[i]) -
			abs(v[i] - v[i + 1]) +
			abs(v[i - 1] - v[i + 1]) << endl;;
	}
}

Measured memory_bytes: 2048