akhauriyash/Code-Regression huggingface dataset:
def main():

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

    v = 1000
    i = 0

    while i < N:
        while i < N-1 and A[i+1] <= A[i]:
            i += 1
        buy = A[i]
        i += 1
        while i < N-1 and A[i+1] >= A[i]:
            i += 1
        if i < N:
            sell = A[i]
            v = (v // buy) * sell + (v - v//buy * buy)
            i += 1
    return v

if __name__ == '__main__':
    print(main())


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

int main() {
    int a, b;
    cin >> a >> b;

    if(a - 2*b > 0)
        cout << a - 2 *b << endl;
    else
        cout << 0 << endl;

    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
long mod=1000000007;
long modpow(long modpow_x,long modpow_y) {
  long modpow_return=1;
  for(long i=1;i<=modpow_y;i*=2) {
    if(modpow_y/i%2==1) modpow_return=modpow_return*modpow_x%mod;
    modpow_x=modpow_x*modpow_x%mod;
  }
  return modpow_return;
}
int main() {
  long n;
  bool o=true;
  cin >> n;
  vector<long> a(n);
  vector<long> b(n);
  for(long i=0;i<n;i++) cin >> a[i];

  for(long i=0;i<n;i++) b[a[i]]++;
  for(long i=0;i<n;i++) {
    if(i%2==0&&n%2==1) {
      if(i==0&&b[i]!=1) o=false;
      if(i!=0&&b[i]!=2) o=false;
    } else if(i%2==1&&n%2==0) {
      if(b[i]!=2) o=false;
    } else {
      if(b[i]!=0) o=false;
    }
  }

  if(o) cout << modpow(2,n/2) << endl;
  else cout << 0 << endl;
}

Measured memory_bytes: 4780
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input(): return sys.stdin.readline().rstrip()

def main():
    K,N=map(int,input().split())
    A=list(map(int,input().split()))
    A=[A[-1]-K]+A+[A[0]+K]
    ans=0
    for i in range(N+1):
        ans=max(ans,A[i+1]-A[i])
    print(K-ans)

if __name__ == '__main__':
    main()


Measured memory_bytes: 76788
import java.util.*;

public class Main {
	public static void main(String[] args) {
      Scanner sc =new Scanner(System.in);
      int N = sc.nextInt();
      int[] p = new int[N];
      int max =0,total =0,chance =1;
      for (int i=0; i<N; i++) {
        p[i] = sc.nextInt();
        max = Math.max(p[i],max);
      }
      for (int i=0; i<N; i++) {
        if(p[i] == max && chance != 0) {
          p[i] /= 2;
          chance--;
        }
        total += p[i];
      }
      System.out.println(total); 
    }
}

Measured memory_bytes: 22868
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <string>

using namespace std;

typedef long long LL;
typedef unsigned int UI;

#define rSort(a) 		sort(a.rbegin(),a.rend())
#define Sort(a) 		sort(a.begin(),a.end())
#define Reverse(a) 		reverse(a.begin(),a.end())
#define Sum(a)  		accumulate(a.begin(), a.end(), 0)
#define REP(i, n) 		for(UI i = 0;i < n;i++)
#define REPR(i, n) 		for(UI i = n;i >= 0;i--)
#define FOR(i, m, n) 	for(UI i = m;i < n;i++)
#define pb(i) 			push_back(i)

#define MOD  			(LL)1e9 + 7;
#define INF  			(LL)1 << 62;



int main(int argc, const char * argv[]) {

	cin.tie(0);
	ios::sync_with_stdio(false);

	int D;
	string ans;

	cin >> D;

	if(D==22){
		ans = "Christmas Eve Eve Eve";
	}else if(D==23){
		ans = "Christmas Eve Eve";
	}else if(D==24){
		ans = "Christmas Eve";
	}else if(D==25){
		ans = "Christmas";
	}

	cout << ans << endl;

	return 0;

}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <string>
#include <numeric>
#include <cmath>

#define rep(i, n) for (int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
using P = pair<ll, ll>;

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

const ll MOD = 1000000007;
const int INF = 1<<30;
//const ll INF = (ll)1e18 + 1;

int main(){
  int N; cin >> N;
  vector<int> a(N);
  rep(i, N) {
    cin >> a[i];
    a[i]--;
  }

  vector<int> ans(N);
  rep(i, N){
    ans[a[i]] = i + 1;
  }
  rep(i, N) cout << ans[i] << " ";
  cout << endl;
}


Measured memory_bytes: 1664
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<cstdio>
#include<cmath>
#include<deque>
#include<numeric>
#include<queue>
#include<stack>
#include<cstring>
#include<limits>
#include<functional>
#include<unordered_set>
#include<iomanip>
#include<cassert>
#include<regex>
#include<bitset>
#include<complex>
#include<chrono>
#include<random>
#define rep(i,a) for(int i=(int)0;i<(int)a;++i)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(),x.end()
using ll=long long;
constexpr ll mod = 1e9 + 7;
constexpr ll INF = 1LL << 60;

ll gcd(ll n, ll m) {
	ll tmp;
	while (m!=0) {
		tmp = n % m;
		n = m;
		m = tmp;
	}
	return n;
}

ll lcm(ll n, ll m) {
	return abs(n * m) / gcd(n, m);//gl=xy
}
 
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
 
using namespace std;


//ここから

ll dp[105][10];
void solve(){
  int h,w,k;
  cin>>h>>w>>k;
  memset(dp,0,sizeof(dp));
  dp[0][0]=1;
  rep(i,h){
    for(int bit=0;bit<(1<<(w-1));++bit){
      bool ng=false;
      rep(j,w-2){
        if(bit&(1<<j)){
          if(bit&(1<<(j+1)))ng=true;
        }
      }
      if(ng)continue;
      rep(j,w){
        bool flag=true;
        if(j>0&&bit&(1<<(j-1)))dp[i+1][j-1]+=dp[i][j],dp[i+1][j-1]%=mod,flag=false;
        if(j<w-1&&bit&(1<<j))dp[i+1][j+1]+=dp[i][j],dp[i+1][j+1]%=mod,flag=false;
        if(flag) dp[i+1][j]+=dp[i][j],dp[i+1][j]%=mod;
      }
    }
  }
  cout<<dp[h][k-1];
}

int main(){
	ios::sync_with_stdio(false);
  cin.tie(0);
	cout<<fixed<<setprecision(15);
  solve();
	return 0;
}


Measured memory_bytes: 256
import math
mod = 10**9 + 7

# http://cav-inet.hateblo.jp/entry/2017/02/18/165141
def binary_search(list,target): 

	result = -1
	left = 0
	right = len(list) - 1

	while left <= right:
		center = (left + right)//2
		if list[center] == target:
			result = center
			break
		elif list[center] < target:
			left = center + 1
		elif list[center] > target:
			right = center - 1

	if result == -1:
		return False
	else:
		return True

n,m = map(int,input().split())
a = [int(input()) for _ in range(m)]

dp = [0] * (n+1)
dp[0] = 1
dp[1] = 1
if binary_search(a,1):
    dp[1] = 0
    
for i in range(2,n+1):
    if binary_search(a,i):
        continue
    dp[i] = (dp[i-1] + dp[i-2]) % mod

print(dp[n])

Measured memory_bytes: 52056
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
#define MA 200000
using namespace std;
map <int, int> mp;
int main() {
  int n, m;
  scanf("%d", &n);
  rep(i, n) {
    int d;
    scanf("%d", &d);
    mp[d]++;
  }
  scanf("%d", &m);
  rep(i, m) {
    int t;
    scanf("%d", &t);
    if (mp[t] == 0) {
      puts("NO");
      return 0;
    }
    mp[t]--;
  }
  puts("YES");
  return 0;
}


Measured memory_bytes: 9600
#include<bits/stdc++.h>
using namespace std;
#define int long long
int N;
int Ans=0;
void dfs(int num,int a,int b,int c)
{
	if(num>N) return;
	if(a&&b&&c) ++Ans;
	dfs(num*10+3,1,b,c);
	dfs(num*10+5,a,1,c);
	dfs(num*10+7,a,b,1);
	return;
}
signed main()
{
	cin>>N;
	dfs(0,0,0,0);
	cout<<Ans<<endl;
	return 0;
}

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

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T> using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;

const ll INF = 1LL<<60;
const ll MOD = 1e9 + 7;

int main() {
    int n;
    cin >> n;
    set<int> s;
    rep(i, n) {
        int d;
        cin >> d;
        s.insert(d);
    } 
    cout << s.size() << endl;
    return 0;
}

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

#define ll long long

int main(){	
	int n;
	cin>>n;
	string s;
	cin>>s;
	int c=1;
	for (int i = 1; i < s.length(); ++i)
	{
		/* code */
		if(s[i]==s[i-1]);
		else
			c++;
	}
	cout<<c<<endl;
	return 0;
}


Measured memory_bytes: 512
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a,b,c;
    cin >> a >> b >> c;
    int odd= 0, eve = 0;
    if(a%2)
        odd++;
    else
        eve++;
    if(b%2)
        odd++;
    else
        eve++;
    if(c%2)
        odd++;
    else
        eve++;
    //vector<int>v;
    if(a%2==0 && b%2==0 && c%2==0)
    {
        int cnt = 0;
        while(1)
        {
            if(a==b && b==c)
                break;
            vector<int>v;
            v.push_back(a);
            v.push_back(b);
            v.push_back(c);
            sort(v.begin(),v.end());
            a = v[0]+2;
            b = v[1];
            c = v[2];
            cnt++;
        }
        cout << cnt << endl;

    }
    else if(a%2!=0 && b%2!=0 && c%2!=0)
    {
        int cnt = 0;
        while(1)
        {
            if(a==b && b==c)
                break;
            vector<int>v;
            v.push_back(a);
            v.push_back(b);
            v.push_back(c);
            sort(v.begin(),v.end());
            a = v[0]+2;
            b = v[1];
            c = v[2];
            cnt++;
        }
        cout << cnt << endl;

    }
    else
    {
        if(odd<eve)
        {
            int cnt = 1;
            if(a%2)
                b++,c++;
            else if(b%2)
                a++,c++;
            else if(c%2)
                a++,b++;
            while(1)
            {
                if(a==b && b==c)
                    break;
                vector<int>v;
                v.push_back(a);
                v.push_back(b);
                v.push_back(c);
                sort(v.begin(),v.end());
                a = v[0]+2;
                b = v[1];
                c = v[2];
                cnt++;
            }
            cout << cnt << endl;



        }

        else
        {
            int cnt = 1;
            if(a%2==0)
                b++,c++;
            else if(b%2==0)
                a++,c++;
            else if(c%2==0)
                b++,a++;
            while(1)
            {
                if(a==b && b==c)
                    break;
                vector<int>v;
                v.push_back(a);
                v.push_back(b);
                v.push_back(c);
                sort(v.begin(),v.end());
                a = v[0]+2;
                b = v[1];
                c = v[2];
                cnt++;
            }
            cout << cnt << endl;



        }

    }

}


Measured memory_bytes: 3576
#include <iostream>
#include <algorithm>
#include <list>
#include <string>
using namespace std;

bool isMissing(string word, int number)
{
	if (number % 15 == 0) return word != "FizzBuzz";
	if (number % 3 == 0) return word != "Fizz";
	if (number % 5 == 0) return word != "Buzz";
	return word != to_string(number);
}

int main()
{
	int m, n;
	while (cin >> m >> n, m + n)
	{
		string words[10001];
		list<int> member;

		for (int i = 1; i <= n; i++) cin >> words[i];
		for (int i = 1; i <= m; i++) member.push_back(i);

		auto nowPlayer = member.begin();
		for (int i = 1; i <= n; i++)
		{

			if (isMissing(words[i], i)) nowPlayer = member.erase(nowPlayer);
			else nowPlayer++;
			if (nowPlayer == member.end()) nowPlayer = member.begin();

			if (member.size() == 1) break;
		}

		auto i = member.begin();
		cout << *i;
		for (i++; i != member.end(); i++)
		{
			cout << ' ' << *i;
		}
		cout << endl;
	}

	return 0;
}

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

int main () {
    // string a, b, c;
    string a;
    cin >> a;
    int sum = 0;
    for (int i = 0; i < a.size(); i++) {
        sum += stoi(a.substr(i,1));                                             
    } 
    if (stoi(a) % sum == 0) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }   
}



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

int main() {
	 
    ll a,b,h,m;
    cin>>a>>b>>h>>m;
    ll hrs=h*5+5*m/60;
    //cout<<m<<" "<<hr<<endl;
    ll angl=6*abs(hrs-m);
    angl=min(360-angl,angl);
    ll cur_ans=a*a+b*b-(2*a*b*cos ( angl * pi / 180.0 ));
    ll finans=sqrt(cur_ans);
    cout<<setprecision(15)<<finans<<endl;
	return 0;
}


Measured memory_bytes: 4120
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
 
int main() {
    int n;
    cin >> n;
    set<string> gacha;
    string s;
    rep(i,n){
        cin >> s;
        gacha.insert(s);
    }
    cout << gacha.size() << endl;
    
return 0;
}


Measured memory_bytes: 19228
s = gets.chomp.split('')
arr = Array.new(s.length)
arr.fill(0)
len = s.length
tmp = ''
subs = []
starts = []
(len - 1).times do |i|
  s1, s2 = s[i], s[i + 1]
  tmp += s1
  if s1 == 'L' && s2 == 'R' || i + 2 >= len
    tmp += 'L' if i + 2 >= len
    subs.push(tmp)
    tmp = ''
  end
  if s1 == 'R' && s2 == 'L'
    starts.push(i)
  end
end
subs.each do |sub|
  start_index = starts.shift
  sub_len = sub.length
  if sub_len % 2 == 0
    arr[start_index] = sub_len / 2
    arr[start_index + 1] = sub_len / 2
  else
    r_count, l_count = sub.count('R'), sub.count('L')
    arr[start_index] = (sub_len / 2).to_i
    arr[start_index + 1] = (sub_len / 2).to_i
    if start_index % 2 == 0
      if r_count % 2 == 0
        arr[start_index + 1] += 1
      else
        arr[start_index] += 1
      end
    else
      if l_count % 2 == 0
        arr[start_index] += 1
      else
        arr[start_index + 1] += 1
      end
    end
  end
end
puts arr.join(' ')

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

int main(){
  string s;
  cin>>s;
  bool n=0,w=0,so=0,e=0;
  for(int i=0;i<s.size();i++){
    if(s[i]=='N') n=1;
    else if(s[i]=='S') so=1;
    else if(s[i]=='W') w=1;
    else e=1;
  }
  
  if(n==so&&w==e) cout<<"Yes"<<endl;
  else cout <<"No"<<endl;
  
}

Measured memory_bytes: 256
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <tuple>
#include <algorithm>
#include <functional>
#include <cstring>
#include <limits.h>
#include <bitset>
#include <complex>
#include <cassert>
#define FOR(i,k,n)  for (int i=(k); i<(int)(n); ++i)
#define REP(i,n)    FOR(i,0,n)
#define FORIT(i,c)	for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define SZ(i) ((int)i.size())
#define GI(i) (scanf("%d",&i))
#define GLL(i) (scanf("%lld",&i))
#define GD(i)  (scanf("%lf",&i))
#define PB          push_back
#define MP          make_pair
#define MT          make_tuple
#define GET0(x)     (get<0>(x))
#define GET1(x)     (get<1>(x))
#define GET2(x)     (get<2>(x))
#define ALL(X)      (X).begin(),(X).end()
#define LLMAX       (1LL<<60)
#define LLMIN       -(1LL<<60)
#define IMAX        (1<<30)
#define IMIN        -(1<<30)
typedef long long LL;
using namespace std;

int main(void){
    int N;
    LL C;
    GI(N);GLL(C);
    vector<LL> X(N),V(N);
    REP(i,N){
        GLL(X[i]);GLL(V[i]);
    }
    vector<LL> left;
    vector<LL> right;
    LL sumc = 0;
    REP(i,N){
        // printf("i=%d V[i]=%lld X[i]=%lld\n",i,V[i],X[i]);
        if(i==0){
            sumc = V[i] - X[i];
        }else{
            sumc += V[i] - X[i] + X[i-1];
        }

        left.PB(sumc);
        // printf("i=%d sumc=%lld\n",i,sumc);
    }
    sumc = 0;
    for(int i = N-1; 0<=i; i--){
        if(i == N-1)
            sumc = V[i] - C + X[i];
        else
            sumc += V[i] + X[i] - X[i+1];
        right.PB(sumc);
    }
    LL ans = max((LL)0, max(left[N-1],right[N-1]));
    {
        priority_queue<LL> qu;
        qu.push(0);
        for(int li=N-1;0<=li;li--){
            LL r = left[li];
            r += max((LL)0, qu.top() - X[li]);
            qu.push(right[N-1-li]);
            ans = max(r,ans);
        }
    }
    {
        priority_queue<LL> qu;
        qu.push(0);
        for(int ri=N-1;0<=ri;ri--){
            LL r = right[ri];
            r += max((LL)0, qu.top() - C + X[(N-1-ri)]);
            qu.push(left[N-1-ri]);
            ans = max(r,ans);
        }
    }

    printf("%lld\n",ans);
    return 0;
}

Measured memory_bytes: 5220
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define zero_pad(num) setfill('0') << std::right << setw(num)
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;

int main() {
    int n, m;
    cin >> n >> m;
    vector<int> h(n);
    rep(i, n)cin >> h[i];
    vector<vector<int>> to(n);
    rep(i, m){
        int a, b;
        cin >> a >> b;
        a--;
        b--;
        to[a].push_back(b);
        to[b].push_back(a);
    }

    int ans = 0;
    rep(i, n){
        if(to[i].size() == 0){
            ans++;
            continue;
        }
        bool valid = true;
        for(int t : to[i]){
            if(h[i] <= h[t])valid = false;
        }
        if(valid)ans++;
    }
    cout << ans << endl;
}

Measured memory_bytes: 8804
N = int(input())
Zlist=[]
Wlist = []
for i in range(N):
    x,y = map(int,input().split())
    z = x+y
    w = x-y
    Zlist.append(z)
    Wlist.append(w)
Zlist.sort()
Wlist.sort()
print(max(Zlist[-1]-Zlist[0],Wlist[-1]-Wlist[0]))

Measured memory_bytes: 25780
#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

char str[6];

int main() {
  int n, k;
  cin >> n >> k;
  int d[k];
  for (int i = 0; i < k; i++) {
    cin >> d[i];
  }
  sprintf(str, "%d", n);
  int payment = n;
  while(1) {
    sprintf(str, "%d", payment);
    int flg = 0;
    for (int i = 0; i < k; i++) {
      for (int j = 0; j < 6; j++) {
        if (str[j] == ('0' + d[i])) {
          flg = 1;
        }
      }
    }
    if (flg == 0) break;
    payment++;
  }
  cout << payment << endl;
}

Measured memory_bytes: 256
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        List<Integer> k = new ArrayList<>();
        for(int x = 1; x <= 9;x++){
            for(int y = 1;y <= 9; y++){
                k.add(x*y);
            }
        }
        for(int x :k){
            if(x ==N){
                System.out.println("Yes");
                sc.close();
                return;
            }
        }
        System.out.println("No");
        
        sc.close();
    }
}


Measured memory_bytes: 23764
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  int A,B,C;
  cin >> A >> B >> C;
  int ans=0;
  if(A==B){
    if(A!=C) ans++;
  }
  if(A==C){
    if(A!=B) ans++;
  }
  if(B==C){
    if(A!=B) ans++;
  }
  if(ans>0) cout << "Yes";
  else cout << "No";
}

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

int main() {
  int K, S, count = 0;
  cin >> K >> S;
  
  for (int X = 0; X <= K; X++) {
    for (int Y = 0; Y <= K; Y++) {
        if ((S - X - Y >= 0) && (S - X - Y <= K)) count++;
    }
  }
  cout << count << endl;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#include<ext/rope>
#define REP(x,y,z) for(int x=y;x<=z;x++)
#define FORD(x,y,z) for(int x=y;x>=z;x--)
#define MSET(x,y) memset(x,y,sizeof(x))
#define FOR(x,y) for(__typeof(y.begin()) x=y.begin();x!=y.end();x++)
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define SZ size()
#define M 500005
void RI(){}
template<typename... T>
void RI( int& head, T&... tail ) {
    scanf("%d",&head);
    RI(tail...);
}
using namespace std;
using namespace __gnu_cxx;
typedef long long LL;
int n,q;
rope<char> in[M],t1,t2;
char buf[M*2];
int main()
{
	int a,b,c,d;
	int z;
	RI(n, q);
	REP(i,1,n)
	{
		scanf("%s", buf);
		in[i] = buf;
	}

	while(q--)
	{
		RI(z);
		if(z==1)
		{
			RI(a,b,c,d);
			
			t1 = in[a].substr(b-1, in[a].length()-b+1);
			t2 = in[c].substr(d-1, in[c].length()-d+1);
			
			in[a] = in[a].substr(0,b-1) + t2;
			in[c] = in[c].substr(0,d-1) + t1;
		}
		else
		{
			RI(a,b);
			scanf("%s", buf);

			t1 = buf;

			int len = in[a].length();
			in[a] = in[a].substr(0,b-1) + t1 + in[a].substr(b, len-b);
		}
	}

	REP(i,1,n) printf("%s\n", in[i].c_str());
	return 0;
}

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

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define DIM (long long)1000007
#define INF (long long)100000007

using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> pairll;

ll n,m,i,j,sum,f1,f2,v1,v2,k,x,y,l,nn,z,kek;
vector<ll> a[DIM];
ll mod=(ll)1e9+7;
ll b[DIM];
ll w[DIM];

void dfs(ll v,ll par){
    if(a[v].size()==1 && a[v][0]==par){
        b[v]=1;
        w[v]=1;
        return;
    }

    ll kek=1;
    ll lol=1;
    for(auto to:a[v]){
        if(to!=par) dfs(to,v);
        else continue;

        if(kek==0) kek=1;
        kek*=w[to];
        if(kek>=mod) kek%=mod;

        if(lol==0) lol=1;
        lol*=(w[to]+b[to]);
        if(lol>=mod) lol%=mod;
    }
    b[v]=kek;
    w[v]=lol;
    //cout << b[v] << " " << w[v] << endl;

}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> n;
    for(i=1; i<n; i++){
        cin >> v1 >> v2;
        a[v1].push_back(v2);
        a[v2].push_back(v1);
    }
    dfs(1,-1);
    cout << (b[1]+w[1])%mod << endl;



    return 0;
}


Measured memory_bytes: 39936
fun main() {
    val n = readLine()!!.toInt()

    val a = IntArray(n + 1) { 0 }
    for (i in 0 until n) {
        a[i + 1] = readLine()!!.toInt()
    }

    var i = 1
    var count = 0
    while (true) {
        count += 1
        i = a[i]
        if (i == 2) {
            print(count)
            return
        }
        if (count == n) {
            break
        }
    }

    print(-1)
}


Measured memory_bytes: 59028
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
#include<map>
using namespace std;
#define fr first
#define sc second
#define rep(i,n) for(int i = 0 ; i < n ; i++ )
typedef pair< int , int > Pt;
typedef long long ll;
const int dx[] = { 0, 1, -1, 0}, dy[] = { 1, 0, 0, -1};
struct P{
  Pt nkmr;
  vector< Pt > pnl,cnt;
};
typedef pair< int , P > IP;
Pt Goal;
int h, w;
char mas[10][10];
int search_cnt(int y,int x,P& n){
  rep(i,n.cnt.size()) if(n.cnt[i] == Pt(y,x)) return i;
  return -1;
}
int search_panel(int y,int x,P& n){
  rep(i,n.pnl.size()) if(n.pnl[i] == Pt(y,x)) return i;
  return -1;
}
bool isused(map<ll,bool>& used,P& p){
  ll ret = (p.nkmr.fr << 4) + p.nkmr.sc;
  for(int i = 0 ; i < p.pnl.size() ; i++ ){
    ret <<= 4;
    ret += p.pnl[i].fr;
    ret <<= 4;
    ret += p.pnl[i].sc;
  }
  for(int i = 0 ; i < p.cnt.size() ; i++ ){
    ret <<= 4;
    ret += p.cnt[i].fr;
    ret <<= 4;
    ret += p.cnt[i].sc;
  }
  if(used[ret]++) return true;
  return false;
}
int bfs(P& St){
  queue<pair< int , P > > que;
  map < ll , bool >  used;
  que.push(IP(0,St));
  while(!que.empty()){
    int _cost = que.front().fr;
    P p = que.front().sc;
    que.pop();
    if(p.nkmr == Goal) return _cost;
    if(isused(used,p)) continue;
    rep(i,4){
      P next = p;
      int ny = p.nkmr.fr + dy[i], nx = p.nkmr.sc + dx[i],contena,panel;
      if(mas[ny][nx] == '#' || search_panel(ny,nx,next) != -1) continue;
      if((contena = search_cnt(ny,nx,next)) != -1){ //コンテナあった
        int ty = ny + dy[i], tx = nx + dx[i];
        if(mas[ty][tx] != '.' || search_cnt(ty,tx,next) != -1) continue;
        while(mas[ty][tx] == '.' &&
              search_cnt(ty,tx,next) == -1 && search_panel(ty,tx,next) == -1){
          ty += dy[i], tx += dx[i];
        }
        if((panel = search_panel(ty,tx,next)) != -1){
          next.cnt[contena] = Pt(-1,-1);
          next.pnl[panel] = Pt(-1,-1);
        }else next.cnt[contena] = Pt(ty - dy[i],tx - dx[i]);
        que.push(IP(_cost,next));
      }else que.push(IP(_cost+1,(P){Pt(ny,nx),p.pnl,p.cnt}));
    }
  }
  return -1;
}
int main(){
  while(cin >> h >> w , h ){
    P p = (P){Pt(),vector<Pt>(),vector<Pt>()};
    int cpa = 0,ccn = 0;
    rep(i,h) rep(j,w){
      cin >> mas[i][j];
      if(mas[i][j] == '@') p.nkmr = Pt(i,j), mas[i][j] = '.';
      else if(mas[i][j] == 'w'){
        p.pnl.push_back(Pt(i,j)), mas[i][j] = '.';
      }else if(mas[i][j] == 'c'){
        p.cnt.push_back(Pt(i,j)), mas[i][j] = '.';
      }else if(mas[i][j] == 'E') Goal = Pt(i,j), mas[i][j] = '.';
    }
    cout << bfs(p) << endl;
  }
}

Measured memory_bytes: 6212
// https://atcoder.jp/contests/apc001/tasks/apc001_c

#include "algorithm"
#include "bitset"
#include "cmath"
#include "functional"
#include "iomanip"
#include "iostream"
#include "map"
#include "numeric"
#include "queue"
#include "set"
#include "string"
#include "vector"
#define rep(i, to) for (ll i = 0; i < (to); ++i)
#define rep1(i, to) for (ll i = 1; i <= (to); ++i)
#define repf(i, from, to) for (ll i = from; i < (to); ++i)
#define repr(i, from) for (ll i = from - 1; i >= 0; --i)
#define all(vec) vec.begin(), vec.end()
#define unless(cond) if (!(cond))
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef long double ld;
template <typename T>
using V = vector<T>;
using VL = V<ll>;
using VVL = V<VL>;
template <typename T, typename U>
using P = pair<T, U>;
using PL = P<ll, ll>;
using VPL = V<PL>;
template <typename T>
inline bool chmax(T& a, T b);
template <typename T>
inline bool chmin(T& a, T b);
void print_ints(vector<ll> v);
template <typename T>
void drop(T a);

const ll INF = 1e18;

void solve() {
  ll N;
  cin >> N;

  string Vacant = "Vacant";
  string Male = "Male";
  string Female = "Female";

  ll left_i = 0;
  cout << left_i << endl;

  string left;
  cin >> left;
  if (left == Vacant) return;

  ll right_i = N - 1;
  cout << right_i << endl;

  string right;
  cin >> right;
  if (right == Vacant) return;

  while (true) {
    ll mid_i = (left_i + right_i) / 2;
    cout << mid_i << endl;

    string mid;
    cin >> mid;
    if (mid == Vacant) return;

    if ((mid_i - left_i) % 2 == 0 && left != mid ||
        (mid_i - left_i) % 2 == 1 && left == mid) {
      right_i = mid_i;
      right = mid;
    } else {
      left_i = mid_i;
      left = mid;
    }
  }
}

struct exit_exception : public std::exception {
  const char* what() const throw() { return "Exited"; }
};

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

  try {
    solve();
  } catch (exit_exception& e) {
  }

  return 0;
}
#endif

template <typename T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}

template <typename T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}

void print_ints(vector<ll> v) {
  rep(i, v.size()) {
    if (i > 0) {
      cout << " ";
    }

    cout << v[i];
  }

  cout << endl;
}

template <typename T>
void drop(T res) {
  cout << res << endl;
  throw exit_exception();
}


Measured memory_bytes: 852
#include <bits/stdc++.h>
using namespace std;
string a;
int n,ac,wa,tle,re;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a;
		if(a=="AC")ac++;
		else if(a=="WA")wa++;
		else if(a=="TLE")tle++;
		else if(a=="RE")re++;
	}
	cout<<"AC x "<<ac<<endl;
	cout<<"WA x "<<wa<<endl;
	cout<<"TLE x "<<tle<<endl;
	cout<<"RE x "<<re<<endl;
}

Measured memory_bytes: 3632
using System;
using System.Text;

namespace DynammicProgramming {
  class LCS {
    public static void Main(string[] args) {
      String s  = Console.ReadLine();
      String t  = Console.ReadLine();

      int[,] dp = new int[s.Length+1, t.Length+1];
      // Init
      for(int row = 0; row <= s.Length; row++) {
        dp[row, 0] = 0;
      }
      for(int col = 0; col <= t.Length; col++) {
        dp[0, col] = 0;
      }
      // Apply Bottom -up dynammic programming approach
      for (int row = 1; row <= s.Length; row++) {
        for (int col = 1; col <= t.Length; col++) {
          // dp[row, col] = Math.Max(dp[row-1, col], dp[row, col-1]);
          dp[row, col] = dp[row-1, col] >= dp[row, col-1] ? dp[row-1, col]  : dp[row, col-1];
          dp[row, col] = Math.Max(dp[row, col], dp[row-1, col-1] + (s[row-1] == t[col-1] ? 1 : 0));
        }
      }

      // Build the answer 
      StringBuilder answer = new StringBuilder();
      int i = s.Length, j = t.Length;
      while(i > 0 && j > 0) {
        if (dp[i, j] == dp[i-1, j]) {
          i = i-1;
        } else if (dp[i,j] == dp[i, j-1]) {
          j = j-1;
        } else {
          answer.Insert(0, s[i-1]);
          i = i-1;
          j = j-1;
        }
      }
      Console.WriteLine(answer.ToString());
    }
  }
}

Measured memory_bytes: 47712
#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stdlib.h>
#include<queue>
#include<map>
#include<vector>
#include<cmath>
#include<fstream>
#include <set>
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
const int  MAXN =1e6+10;
const int mod = 1e9 + 7;
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int inf= 0x3f3f3f3f;
#define eps 1e-8
#define PI 3.1415926535898
#define lowbit(x) (x&(-x))
using namespace std ;
//getline(cin,s);
//set<ll>::iterator it;
//map<int,int>::iterator it;
typedef long long ll;
unordered_map<int,int>mp;
int main()
{
	int x,n;
	scanf("%d %d",&x,&n);
	for(int i=1;i<=n;i++)
	{
		int a;
		scanf("%d",&a);
		mp[a]=1;
	}
	int num=0;
	while(1)
	{
		if(mp[x-num]==0)
		{
			printf("%d\n",x-num);
			return 0;
		}
		if(mp[x+num]==0)
		{
			printf("%d\n",x+num);
			return 0;
		}
		num++;
	}
} 

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

int main() {
	string s;
	cin >> s;
	int len = s.size();
	int cnt = 0;
	for (int i = 0; i < len / 2; ++i) {
		int head = i;
		int tail = len - i - 1;
		if (s[head] != s[tail]) {
			++cnt;
		}
	}
	cout << cnt;
}


Measured memory_bytes: 256
require 'pp'
$DEBUG ? define_method(:dpp){|e|pp e} : define_method(:dpp){|e|}

# 入力値を文字の配列で返却する
def gets_nsp_list()
  gets.chomp.split("")
end
_ = gets
x, max = 0, 0

s_list = gets_nsp_list
s_list.each do |s|
  if s == "I"
    x += 1
  else
    x -= 1
  end
  max = [x, max].max
end

puts max

Measured memory_bytes: 2300
#include <stdio.h>
#include <math.h>
#include <string.h>
#define rep(i,a,b) for(i=a;i<b;i++)

int main(){
	int n,a[110]={};
	scanf("%d",&n);
	int i;
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	for(i=n-1;i>=0;i--){
		if(i!=n-1) printf(" ");
		printf("%d",a[i]);
	}
	printf("\n");
	return 0;
}

Measured memory_bytes: 600
use std::io::prelude::*;
use std::io::stdin;
use std::str::FromStr;

fn main() {
    let n: usize = read();
    let x: i32 = read();
    let l: Vec<i32> = (0..n).map(|_| read()).collect();

    let ans = l
        .iter()
        .scan(0, |state, &x| {
            *state += x;
            Some(*state)
        })
        .filter(|&a| a <= x)
        .count()
        + 1;

    println!("{}", ans);
}

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let token: String = stdin
        .lock()
        .bytes()
        .map(|b| b.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().unwrap()
}


Measured memory_bytes: 4352
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <cstring>
#include <string>
#include <vector>
#include <cmath>
#include <random>
#include <climits>
#include <set>
#include <deque>
#include <queue>
#include <bitset>
#include <stack>

#define mod 1000000007
#define INF2 9999999999
#define INF (1<<30)
#define rep(i,n) for(int (i)=0; (i)<(n); (i)++)
#define P pair<int, int>

using namespace std;
using ll = long long;

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

void solve(){
    int n, ans = 0;
    cin >> n;
    int d, x;
    cin >> d >> x;
    int a[n];
    rep(i, n) cin >> a[i];

    ans += x;
    ans += n;

    rep(i, n){
        for(int j = 1; j <= d; j++){
            if(j*a[i]+1 <= d){
                ans++;
            }else{
                break;
            }
        }
    }
    cout << ans << endl;
    
}

int main(){
    solve();
    return 0;
}


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

#define int long long

typedef pair<int,int>pint;
typedef vector<int>vint;
typedef vector<pint>vpint;
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(v) (v).begin(),(v).end()
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
#define each(it,v) for(__typeof((v).begin()) it=(v).begin();it!=(v).end();it++)
template<class T,class U>void chmin(T &t,U f){if(t>f)t=f;}
template<class T,class U>void chmax(T &t,U f){if(t<f)t=f;}

int N;
int A[111111];
vint G[111111];

int dp[111111];

bool dfs(int v,int p){
    if(G[v].size()==1){
        dp[v]=A[v];
        return true;
    }

    int sa=0;

    vint vec;
    for(auto u:G[v]){
        if(u==p)continue;
        if(!dfs(u,v))return false;
        sa+=dp[u];
        vec.pb(dp[u]);
    }

    if(sa<A[v])return false;
    int r=sa-A[v];
    if(A[v]-r<0)return false;
    int q=A[v]-r;
    sort(all(vec));
    int sum=0;
    for(int i=0;i+1<vec.size();i++)sum+=vec[i];
    if(sum<r)return false;
    dp[v]=q;
    return true;
}

signed main(){
    scanf("%lld",&N);
    rep(i,N)scanf("%lld",&A[i]);
    rep(i,N-1){
        int a,b;
        scanf("%lld%lld",&a,&b);
        a--;b--;
        G[a].pb(b);G[b].pb(a);
    }

    rep(i,N){
        if(G[i].size()>1){
            if(dfs(i,-1)&&dp[i]==0){
                puts("YES");
            }
            else{
                puts("NO");
            }
            return 0;
        }
    }
    assert(N==2);
    if(A[0]==A[1])puts("YES");
    else puts("NO");
    return 0;
}


Measured memory_bytes: 16896
#include <bits/stdc++.h>
#define sz(arr) (int)arr.size()
#define all(arr) arr.begin(), arr.end()

using namespace std;

void _cin() {}
template <class Head, class... Tail>
void _cin(Head&& head, Tail&&... tail) {
  cin >> head;
  _cin(forward<Tail>(tail)...);
}

#define Cin(T, ...) \
  T __VA_ARGS__;    \
  _cin(__VA_ARGS__)

int main() {
  Cin(string, s);

  cout << count(all(s), '1') << endl;

  return 0;
}

Measured memory_bytes: 256
#include<stdio.h>
int main()
{
    int a,b,c;
    while(scanf("%d%d%d",&a,&b,&c) != EOF)
    {
        if(a==b && a==c)
        {
            printf("1\n");
            continue;
        }
        else if((a==b || a==c) && b!=c)
          {
            printf("2\n");
            continue;
        }
        else if((b==c || b==a) && a!=c)
          {
            printf("2\n");
            continue;
        }
        else if((b==c || c==a) && a!=b)
          {
            printf("2\n");
            continue;
        }
        else
        {
            printf("3\n");
        }
    }
    return 0;
}


Measured memory_bytes: 128
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N=sc.nextInt();
        int x=sc.nextInt();
        boolean all=true;
        int remain=x;
        int[] child=new int[N];
        int[] child_sorted;
        int[] sum=new int[N];
        for(int i=0;i<N;i++){
            child[i]=sc.nextInt();
        }
        child_sorted=sentaku(child);
        sum[0]=child_sorted[0];
        for(int i=1;i<child.length;i++){
            sum[i]=sum[i-1]+child_sorted[i];
        }
        for(int i=0;i<sum.length;i++){
            //全員には配れない
            if(x<sum[i]){System.out.println(i);all=false; break;}
        }
        if(all==true){
            if(remain-sum[N-1]==0)System.out.println(N);
            else System.out.println(N-1);
        }
    }
    static int[] sentaku(int[] a){
        int min; int min_index=-1;
        int temp;
        for(int i=0;i<a.length;i++){
            min=Integer.MAX_VALUE;
            for(int j=i;j<a.length;j++){
                if(min>a[j]) {min=a[j]; min_index=j;}
            }
            temp=a[i];
            a[i]=min;
            a[min_index]=temp;
        }
        return a;
    }
}


Measured memory_bytes: 23636
#include <bits/stdc++.h>
using namespace std;
using pii=pair<int,int>;
using ll=long long;

#define fi first
#define se second
#define pb push_back
#define rep(i,n) for(int i=0; i<(int)(n); i++)

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

bool temp(pair<ll,int> a, pair<ll,int> b) {
	if(a.fi > b.fi) return true;
	else return false;
}
int main() {
	int x,y,a,b,c;
	cin >> x >> y >> a >> b >> c;
	vector<ll> p(a),q(b),r(c);
	ll ta,tb,tc;
	rep(i,a) {
		cin >> p[i];
	}
	rep(i,b) {
		cin >> q[i];
	}
	rep(i,c) {
		cin >> r[i];
	}
	sort(p.begin(), p.end(), std::greater<ll>());
	sort(q.begin(), q.end(), std::greater<ll>());
	p.erase(p.begin()+x, p.end());
	q.erase(q.begin()+y, q.end());
	copy(q.begin(), q.end(), std::back_inserter(p));
	copy(r.begin(), r.end(), back_inserter(p));
	sort(p.begin(), p.end(), std::greater<ll>());

	ll ans=0;
	ll t = x+y;
	auto itr = p.begin();
	while (t > 0) {
		ans += *itr;
		//cout << itr->first << " ";
		itr++;
		t--;
	}
	cout << ans << endl;
  return 0;
}


Measured memory_bytes: 5872
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
//INSERT ABOVE HERE
signed main(){
  Int n;
  cin>>n;
  vector<Int> a(n);
  for(Int i=0;i<n;i++) cin>>a[i];
  Int q;
  cin>>q;
  for(Int i=0;i<q;i++){
    Int k;
    cin>>k;
    cout<<lower_bound(a.begin(),a.end(),k)-a.begin()<<" ";
    cout<<upper_bound(a.begin(),a.end(),k)-a.begin()<<endl;
  }
  return 0;
}



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

using namespace std;
typedef long long int lld;


int main(void){
	lld a,b,c,k;
	cin >> a >> b >> c >> k;
	if(a>=k){
		printf("%lld",k);
	}else if(a+b>=k){
		printf("%lld",a);
	}else{
		lld dd = k - a - b;
		lld sol = a - dd;
		printf("%lld",sol); 
	}
	return 0;
}


Measured memory_bytes: 3764
#include <iostream>
#include <vector>

using namespace std;
vector<int> g[100010];
long long a[100010],c=0,sum = 0;

long long dfs(int r,int p){
	if(g[r].size()==1){
		return a[r];
	}
	long long sum = 2*a[r];
	for(int i=0;i<g[r].size();i++){
		if(g[r][i]!=p){
			long long x = dfs(g[r][i],r);
			sum -= x;
			if(x>a[r]){
				c = 1;
			}
		}
	}
	if(sum<0 || sum>a[r]){
		c = 1;
	}
	return sum;
}

int main(){
	int i,n;
	cin >> n;
	for(i=1;i<=n;i++){
		cin >> a[i];
	}
	if(n==2){
		if(a[1]==a[2]){
			cout << "YES" << endl;
		}else{
			cout << "NO" << endl;
		}
		return 0;
	}
	for(i=0;i<n-1;i++){
		int c,b;
		cin >> c >> b;
		g[c].push_back(b);
		g[b].push_back(c);
	}
	for(i=1;i<=n;i++){
		if(g[i].size()==1){
			sum += a[i];
		}
	}
	if(sum%2==1){
		c = 1;
	}
	for(i=1;i<=n;i++){
		if(g[i].size()>1){
			if(dfs(i,0)){
				c = 1;
			}
			break;
		}
	}
	if(c){
		cout << "NO" << endl;
	}else{
		cout << "YES" << endl;
	}
}


Measured memory_bytes: 13184
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		int a = sc.nextInt();
		int b = sc.nextInt();

		if(b*2 > a)
		{
			System.out.println(0);
		}
		else
			System.out.println(a-2*b);
	}
}

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

int main()
{
	string s;
	cin >> s;
	int a=0,out=0;
	for(int i=0;i<3;i++)
	{
		if(s[i]=='R')
		{
			a++;
		}
		else
		{
			
			a=0;
		}
		out=max(out,a);
	}
	//out=max(out,a);
	cout << out;
	return 0;
}

Measured memory_bytes: 3612
#include <iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<math.h>
using namespace std;
typedef long long ll;
#define int long long
typedef vector<int> VI;
typedef pair<int, int> pii;
typedef vector<pii> VP;
typedef vector<string> VS;
typedef priority_queue<int> PQ;
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; }
#define fore(i,a) for(auto &i:a)
#define REP(i,n) for(int i=0;i<n;i++)
#define eREP(i,n) for(int i=0;i<=n;i++)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define eFOR(i,a,b) for(int i=(a);i<=(b);++i)
#define SORT(c) sort((c).begin(),(c).end())
#define rSORT(c) sort((c).rbegin(),(c).rend())
#define LB(x,a) lower_bound((x).begin(),(x).end(),(a))
#define UB(x,a) upper_bound((x).begin(),(x).end(),(a))
#define INF 1000000000
#define LLINF 9223372036854775807
#define mod 1000000007
//priority_queue<int,vector<int>, greater<int> > q2;

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

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

	int N; cin >> N;
	VI A(N*N);
	REP(i, N*N)cin >> A[i];
	int ans = 0;
	int cost[510][510];
	bool F[510][510] = { false };
	REP(i, 510)REP(j, 510)cost[i][j] = -1;
	REP(i, N)REP(j, N) {
		cost[i][j] = min({ i,j,N - i - 1,N - j - 1 });
	}
	
	REP(i, N*N) {
		//cout << A[i] << endl;
		REP(a, 4) {
			//REP(b, 4)cout << cost[a][b] << " ";
			//cout << endl;
		}
		A[i]--;
		int x = A[i] / N, y = A[i] % N;
		ans += cost[x][y];
		cost[x][y]--;
		F[x][y] = 1;
		queue<pii>Q;
		Q.push(pii(x, y));
		while (!Q.empty()) {
			x = Q.front().first, y = Q.front().second;
			Q.pop();
			REP(k, 4) {
				int nx = x + dx[k], ny = y + dy[k];
				if (nx >= 0 && nx < N + 2 && ny >= 0 && ny < N + 2) {
					if (F[nx][ny] && cost[nx][ny] > cost[x][y]) {
						cost[nx][ny] = cost[x][y];
						Q.push(pii(nx, ny));
					}
					else if (cost[nx][ny] > cost[x][y] + 1) {
						cost[nx][ny] = cost[x][y] + 1;
						Q.push(pii(nx, ny));
					}
					
				}
			}
		}

		
	}




	cout << ans << endl;

	return 0;
}



Measured memory_bytes: 7388
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    ll n,val,temp;
    cin>>n;
    ll arr[n+5];
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    val=arr[0];
    for(int i=0;i<n-1;i++)
    {
        val=val^arr[i+1];
    }
    for (int i=0;i<n;i++)
    {
        temp=arr[i]^val;
        cout<<temp<<' ';
    }
    return 0;
}

Measured memory_bytes: 5164
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
using namespace std;
 
#define mod 998244353
#define FOR(x,to) for(int x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define long long long
inline int rei(){int x;cin>>x;return x;}
inline long rel(){long x;cin>>x;return x;}
inline string res(){string x;cin>>x;return x;}
//------------------------------------------------------- 
struct Fact{
	vector<long> f;
	vector<long> rf;
	long pow(long N,long K){
		if(K == 0){
			return 1;
		}
		else if(K % 2 == 0){
			long t = pow(N,K/2);
			return t*t%mod;
		}
		else{
			return N*pow(N,K-1)%mod;
		}
	}
	Fact(int N):f(N+1),rf(N+1){
		for(int i=0;i<N+1;i++){
			if(i == 0){
				f[i] = 1;
			}
			else{
				f[i] = (f[i-1]*i)%mod;
			}
		}
		for(int i=N;i>=0;i--){
			if(i == N){
				rf[i] = pow(f[N],mod-2);
			}
			else{
				rf[i] = rf[i+1]*(i+1)%mod;
			}
		}
	}
	long GetFact(int N){
		return f[N];
	}
	long GetPerm(int N,int R){
		return f[N] * rf[N-R] % mod;
	}
	long GetConv(int N,int R){
		return ((f[N]*rf[R])%mod*rf[N-R])%mod;
	}
	long GetRev(int N){
		if(N == 0){
			return 1;
		}
		else{
			return rf[N] * f[N-1] % mod;
		}
	}
};
void Calc(){
	int N = rei();
	int X = rei();
	long ans = 0;
	Fact F(N);
	for(int i=0;i*2<X;i++){
		for(int j=0;j+i*2<X;j++){
			if(i+j > N){
				break;
			}
			ans += F.GetConv(N,i+j) * F.GetConv(i+j,i) % mod;
		}
	}
	if(X % 2 == 1){
		for(int i=0;i<=N;i++){
			if(i*2 > X){
				ans += F.GetConv(N,i);
			}
		}
	}
	for(int i=X+1;i<=2*N;i+=2){
		int tworow = (i-X+1);
		int s = i-tworow*2;
		for(int t=0;t*2<=s;t++){
			int o = s - t*2;
			if(o+tworow+t > N){
				continue;
			}
			if(o != 0){
				ans += F.GetConv(N,o+tworow+t) * F.GetConv(o+t,t) % mod;
			}
		}
	}
	ans %= mod;
	cout << ans << endl;
}
int main(int argc,char** argv){
	ios::sync_with_stdio(false), cin.tie(0);
	cout.tie(0); Calc(); return 0;
}

Measured memory_bytes: 256
package main

import "fmt"

func main() {
	var d int
	fmt.Scan(&d)
	cs := make([]int, 26)
	for i := 0; i < 26; i++ {
		fmt.Scan(&cs[i])
	}

	ds := make([]int, d)
	as := make([]int, d)
	ss := make([][26]int, d)
	for i := 0; i < d; i++ {
		for j := 0; j < 26; j++ {
			fmt.Scan(&ss[i][j])
			if ds[i] < ss[i][j] {
				ds[i] = ss[i][j]
				as[i] = j
			}
			ds[i] = max(ds[i], ss[i][j])
		}
	}

	for i := 0; i < d; i++ {
		fmt.Println(as[i] + 1)
	}
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}


Measured memory_bytes: 2468
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,n) for(int i=a;i<n;i++)
#define FORR(i,a,n) for(int i=a;i>n;i--)
#define ri(x) scanf("%d",&x)
#define rii(x,y) ri(x), ri(y)
#define S second
#define F first
#define pb push_back
#define mp make_pair
#define db(x) printf("%d\n",x)
typedef long long ll;
int a[200000];
int main(){
	int n;
	ri(n);
	FOR(i,0,n)
		ri(a[i]);
	int l;
	FORR(i,n-1,-1){
		printf("%d ",a[i]);
		i--;
		l=i;
	}
	if(l==0){
		FOR(i,0,n){
			printf("%d ",a[i]);
			i++;
		}
	}
	else{
		FOR(i,1,n){
			printf("%d ",a[i]);
			i++;
		}
	}
	printf("\n");
	return 0;
}


Measured memory_bytes: 2944
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <iomanip>
#include <stack>
#include <queue>
#include <numeric>
#define rep(i,n) for(int i=0;i<(n);i++)
#define pb push_back
#define mod 1000000007
typedef long long ll;
using namespace std;

int main(){
  ll N;
  cin >> N;
  vector<ll> A(N);
  rep(i,N) cin >> A[i];
  ll sum = 0;
  rep(i,N) sum += A[i];
  ll ans = 1e14;
  ll x=0,y;
  for(int i=0;i<N-1;i++){
    x+=A[i];
    y = sum - x;
    ll preans = abs(x-y);
    ans = min(ans,preans);
  }
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 1792
# -*- coding: utf-8 -*-
import sys
from functools import reduce
# ----------------------------------------------------------------
# Use Solve Function

def solve(lines):
    def func(s, i):
        re = s + abs(i - B)
        return re

    N = int(lines.pop(0))
    L = list(map(int, lines.pop(0).split(' ')))
    L = [ x - (i+1) for (i, x) in enumerate(L) ]
    L.sort()
    B = L[int(len(L) / 2)]
    print(reduce(func, L, 0))
    #print(reduce(lambda n, i: n + abs(i - b), L))
    #print(list(map(lambda i:  abs(i - b), L)))

#
# main
#

# 1. use list instead of stdin

# contents = '''\
# 7
# 1 1 1 1 2 3 4\
# '''
# lines = contents.split('\n')

# 2. use stdin

lines = [x.strip() for x in sys.stdin.readlines()]

#
# solve !!
#
solve(lines)

Measured memory_bytes: 25708
#include <iostream>
using namespace std;
int main(){


    int n;
    int gu[n];
    int ki[n];
    int j=0,l=0;
    cin>>n;
    
    for(int i=0;i<n;i++){
        int a;
        cin>>a;
        if(a%2==0){
            gu[j]=a;
            j++;
        }else{
            ki[l]=a;
            l++;
        }
        
    }
    
    if(l==n){
        cout<<0<<endl;
        return 0;
    }
  
    int ans=0;
    
    for(int i=0;i<j;i++){
        int k=0;
        while(gu[i]%2==0){
            gu[i]=gu[i]/2;
            
            k++;
        }
        ans+=k;
    //   cout<<k<<endl;
    }
    
    cout<<ans<<endl;


return 0;
}


Measured memory_bytes: 2304
#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<queue>
#include<map>
#include<math.h>
#include<string>
#include <cctype>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define reps(i, s, n) for (int i = s; i < (int)(n); i++)
#define out(x) cout << x << endl
#define INF 1ll<<60;

using namespace std;
using ll = long long;
typedef pair<int, int> P;

int main(){
    int x, y, z;
    cin >> x >> y >> z;
    if(x%(y+z)<z) out(x/(y+z)-1);
    else out(x/(y+z));
}

Measured memory_bytes: 256