akhauriyash/Code-Regression huggingface dataset:
N = int(input())
P = list(map(int, input().split()))

dist = [P[i-1] - i for i in range(1, N+1)]

count = 0

for i in range(N):
    if dist[i] == 0:
        count += 1
        if i < N-1:
            dist[i] -= 1
            dist[i+1] += 1
        else: # i == N-1
            dist[i] += 1
            dist[i-1] -= 1
    
print(count)

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

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n;
    cin>>n;
    if(n%2==0)
    {
        cout<<n/2-1;
    }
    else
    {
        cout<<n/2;
    }
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 5;
int n,a,b;
int mn,mx;
int cnt[maxn];
deque<int> res, t;
int main() {
    int cur;
    scanf("%d%d%d",&n,&a,&b);
    mn = min(a,b); mx = max(a,b);
    cnt[0] = mn;
    for(int i=mn+1,pos=0;i<=n;i++) {
        if(pos==0) pos = (pos+1)%mx;
        cnt[pos]++;
        pos = (pos+1)%mx;
    }
    for(int i=0,cur=0;i<mx;i++) {
        if(cnt[i]==0 || cnt[i]>mn) return !printf("-1");
        t.clear();
        while(cnt[i]--) t.push_front(++cur);
        for(auto x : t) res.push_back(x);
    }
    if(a<b) reverse(res.begin(),res.end());
    for(auto x : res) printf("%d ",x);
}


Measured memory_bytes: 4096
#include <bits/stdc++.h>
using namespace std;
#define fo(i,a,b) for(int i=(a);i<(b);i++)
#define MOD 1000000007
#define MP make_pair
#define PB push_back
typedef long long ll;

int N, a[200200], l[200200], r[200200];
stack<pair<int, int>> s;

ll ans;

int main () {
        scanf("%d", &N);
        fo(i, 0, N) scanf("%d", &a[i]);

        fo(i, 0, N) {
                while (s.size() && s.top().second > a[i]) s.pop();
                l[i] = s.size() ? s.top().first : -1;
                s.push(MP(i, a[i]));
        }
        while (s.size()) s.pop();

        for (int i = N; i--; ) {
                while (s.size() && s.top().second > a[i]) s.pop();
                r[i] = s.size() ? s.top().first : N;
                s.push(MP(i, a[i]));
        }

        fo(i, 0, N) {
                ll x = i - l[i];
                ll y = r[i] - i;
                ans += x * y * a[i];
        }

        printf("%lld\n", ans);

        return 0;
}


Measured memory_bytes: 4224
def check(y,x):
    if 0<=y<=h-1 and 0<=x<=w-1:
        return True
    return False

h,w=map(int,raw_input().split())
g=[map(int,raw_input().split()) for _ in xrange(h)]
pos=[-1]*(h*w)
for i in xrange(h):
    for j in xrange(w):
        pos[g[i][j]-1]=[i,j]

dy=(1,0,-1,0)
dx=(0,1,0,-1)
stop=[set() for _ in xrange(h*w)]
ans=0
for i in xrange(h*w):
    y,x=pos[i]
    for j in xrange(4):
        ny=y+dy[j];nx=x+dx[j]
        if check(ny,nx):
            if g[ny][nx]<g[y][x]:
                for k in list(stop[g[ny][nx]-1]):
                    stop[i].add(k)
    cnt=len(stop[i])
    if cnt>=2:
        ans+=1
    elif cnt==0:
        stop[i].add(g[y][x])

print(ans)

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

typedef long long ll;
const int MAXN = 100010;
const ll inf = 0x3f3f3f3f3f3f3f3f;

int n, a[MAXN];
char op[MAXN][5];
ll f[MAXN][3];

int main()
{
	scanf("%d", &n);
	for(int i = 1; i < n; ++i) scanf("%d %s", &a[i], op[i]);
	scanf("%d", &a[n]);
	f[1][0] = a[1], f[1][1] = f[1][2] = -inf;
	for(int i = 2; i <= n; ++i)
	{
		if(op[i - 1][0] == '+')
		{
			f[i][0] = max(f[i - 1][0] + a[i], f[i - 1][1] + a[i]);
			f[i][1] = f[i - 1][1] - a[i];
			f[i][2] = f[i - 1][2] + a[i];
		}
		else
		{
			f[i][0] = -inf;
			f[i][1] = max(f[i - 1][0] - a[i], f[i - 1][1] - a[i]);
			f[i][2] = max(f[i - 1][1] + a[i], f[i - 1][2] + a[i]);
		}
	}
	printf("%lld\n", max(f[n][0], max(f[n][1], f[n][2])));
	return 0;
}

Measured memory_bytes: 3456
MOD = 10**9 + 7
n = int(input())
if n == 1:
	print(1)
else:
	dp = [0 for _ in range(n+1)]
	dp[0], dp[1], dp[2] = 1, 1, 1
	cum = [0 for _ in range(n+1)]
	cum[0], cum[1], cum[2] = 1, 2, 3
	for i in range(3, n+1):
		dp[i] = (dp[i-1] + cum[i-3]) % MOD
		cum[i] = (cum[i-1] + dp[i]) % MOD
	ans = cum[n-2] * (n-1) * (n-1) + dp[n-1] * (n-1) + cum[n-2] * (n-1) + 1
	print(ans%MOD)

Measured memory_bytes: 82276
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using p = pair<int, int>;
#define INF 1000000000
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repX(i, n ,x) for (int i = x; i < (int)(n); i++)
#define repBack(i, n) for (int i = n; i > 0; i--)

int main() {
    string S;
    cin >> S;
    string T;
    cin >> T;
    int ans = 0;
    rep(i,3)if(S[i]==T[i])ans ++;
    cout << ans << endl;

    return 0;
}

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

int main() {
  int N;
  int M;
  int sum=0;
  cin >> N >> M;
   for (int i = 0; i < M; i++) {
     int Ai;
     cin >> Ai;
     sum +=Ai;
  }
  if (sum > N){
    cout << "-1" << endl;
  }
  else {
    cout << N-sum << endl;
  }
}


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

int main() {
  int N;
  cin >> N;
  int sum = 0;
  for (int i = 0; i < N; i++) {
    int l, r;
    cin >> l >> r;
    sum += r-l+1;
  }
  
  cout << sum << endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1000000007;


int main() {
    int H, W;
    cin >> H >> W;
    vector<string>M(H);
    for (size_t i = 0; i < H; i++)
    {
        cin >> M.at(i);
    }
    for (size_t i = 0; i < H; i++)
    {
        for (size_t j = 0; j < W; j++)
        {
            if (M.at(i).at(j) != '.') {
                if (i != 0 && M.at(i - 1).at(j) == '#')continue;
                if (i != H - 1 && M.at(i + 1).at(j) == '#')continue;
                if (j != 0 && M.at(i).at(j - 1) == '#')continue;
                if (j != W - 1 && M.at(i).at(j + 1) == '#')continue;
                //cout << i << endl << j << endl;
                cout << "No";
                return 0;
            }
        }
    }
    cout << "Yes";
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
 
int main() {
    int N, L;
    cin >> N >> L;
    int minv = 1000;
    int sum = 0;
    for (int i = 0; i < N; i++)
    {
        int val = i+L;
        if(abs(val) < abs(minv)){
            minv = val;
        }
        sum += val;
    }
    cout << (sum - minv)<<endl;
    return 0;
}

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

int main()
{
  int n, m;
  cin >> n >> m;
  vector<vector<int>> s(m, vector<int>(0));
  for (int i = 0; i < m; i++) {
    int k;
    cin >> k;
    for (int j = 0; j < k; j++) {
      int s_cache;
      cin >> s_cache;
      s.at(i).push_back(s_cache);
    }
  }
  vector<int> p(m);
  for (int i = 0; i < m; i++) {
    cin >> p.at(i);
  }
  int count = 0;
  for (int i = 0; i < 1 << n; i++) {
    int flag = 1;
    for (int j = 0; j < m; j++) {
      int on = 0;
      for (int k = 0; k < s.at(j).size(); k++) {
        if (i & (1 << (s.at(j).at(k) - 1))) on++;
      }
      if ((on - p.at(j)) % 2 != 0) {
        flag = 0;
        break;
      }
    }
    count += flag;
  }
  cout << count << endl;
}


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

int main() {
    int x;
    cin >> x;
    if(x>=30) cout << "Yes" << endl;
    else cout << "No" << endl;
}


Measured memory_bytes: 3640
import sys,queue,math,copy,itertools,bisect,collections
from heapq import *

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())

    N = NI()
    root = [[] for _ in range(N)]
    for _ in range(N-1):
        a,b = LI()
        root[a-1].append(b-1)
        root[b-1].append(a-1)

    node = [-1 for _ in range(N)]
    q = []
    q.append((0,0))
    node[0] = 0
    while q:
        u,num = q.pop()
        for v in root[u]:
            if node[v] < 0:
                node[v] = num+1
                if v == N-1:
                    q = []
                    break
                q.append((v,num+1))
    c = node[N-1]
    u = N-1
    pu = 0
    while c > (node[N-1])//2:
        for v in root[u]:
            if node[v] != c-1: continue
            pu = u
            u = v
            c -= 1
            break

    p = u
    node = [-1 for _ in range(N)]
    node[p] = 0
    node[pu] = 1
    cnt = [0,0]
    for i in range(2):
        if i == 0:
            q.append(p)
        else:
            q.append(pu)
        while q:
            u = q.pop()
            for v in root[u]:
                if node[v] < 0:
                    node[v] = i
                    q.append(v)
                    cnt[i] += 1
    if cnt[0] > cnt[1]:
        print('Fennec')
    else:
        print('Snuke')

if __name__ == '__main__':
    main()

Measured memory_bytes: 62252
#include<bits/stdc++.h>
#include<string.h>
 
typedef long long int ll;
#define all(x) (x).begin(), (x).end()
 
using namespace std;

int nxt() {
    int x;
    cin >> x;
    return x;
}

ll nxtl(){
    ll x;
    cin>>x;
    return x;
}
 
void SieveOfEratosthenes(int n,vector <int> &primes) 
{ 
    // Create a boolean array "prime[0..n]" and initialize 
    // all entries it as true. A value in prime[i] will 
    // finally be false if i is Not a prime, else true. 
    bool prime[n+1]; 
    memset(prime, true, sizeof(prime)); 
  
    for (int p=2; p*p<=n; p++) 
    { 
        // If prime[p] is not changed, then it is a prime 
        if (prime[p] == true) 
        { 
            // Update all multiples of p greater than or  
            // equal to the square of it 
            // numbers which are multiple of p and are 
            // less than p^2 are already been marked.  
            for (int i=p*p; i<=n; i += p) 
                prime[i] = false; 
        } 
    } 
  
    // Print all prime numbers 
    for (int p=2; p<=n; p++) 
       if (prime[p]) 
          primes.push_back(p);
} 
 
ll max(ll a,ll b)
{
    if(a>b)
        return a;
    return b;
}
 
ll power(ll x, ll y,ll mod) 
{ 
    ll temp; 
    if( y == 0) 
        return 1; 
    temp = power(x, y/2,mod); 
    if (y%2 == 0) 
        return (temp*temp)%mod; 
    else
        return (((x*temp)%mod)*temp)%mod; 
} 

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n=nxt();int m=nxt();
    vector <pair<int,int> > v;
    map <int,int> s;
    for(int i=0;i<m;i++)
    {
        int p=nxt();
        string s2;cin>>s2;
        if(s2=="WA")
            v.push_back({p,i});
        else
        {
            if(s.count(p)==0)
                s[p]=i;
        }
    }
    int c=0;
    for(int i=0;i<v.size();i++)
        if(s.count(v[i].first)&&s[v[i].first]>v[i].second)
            c++;
    cout<<s.size()<<" "<<c<<endl;
  

    return 0;   
}


 
 


Measured memory_bytes: 4992
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string str;
  cin>>str;
  int n;
  cin>>n;
  for(int i=0;i<n;i++)
  {
    string meirei,t;
    int a,b;
    cin>>meirei>>a>>b;
    if(meirei=="replace")
    {
      cin>>t;
      int l=str.length();
      str=str.substr(0,a)+t+str.substr(b+1,l-b);
    }
    if(meirei=="print")
    {
      string tmp=str.substr(a,b-a+1);
      cout<<tmp<<endl;
    }
    if(meirei=="reverse")
    {
      string tmp="";
      int l=str.length();
      for(int i=b;i>=a;i--)
        tmp+=str[i];
      str=str.substr(0,a)+tmp+str.substr(b+1,l-b);
    }
  }
}

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

int main() {
    int a, b, c;
    cin >> a >> b >> c;
    if ((a == 5 and b == 5 and c == 7) or (a == 5 and b == 7 and c == 5) or (a == 7 and b == 5 and c == 5)){
        cout << "YES" << endl;
    }else{
        cout << "NO" << endl;
    }
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
typedef long long  ll;
#define press_F_to_pay_respect ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define forn for(int i=0;i<n;i++) 
#define form for(int j=0;j<n;j++) 
#define fora(i,a,b) for(int i = a; i < (b); i++)
#define pb push_back 
#define pob pop_back()
#define mp make_pair 
#define sc second 
#define f first 
#define kek cout<<endl; 
#define all(v) ((v).begin()), ((v).end()) 
#define pob pop_back() 
#define halt {cout<<-1; return 0;}
const ll MOD = 1e9 + 7;
const int N = 300010;
const ll INF = 1e8;
const ll MOD1=998244353;
using namespace std;
bool comp(string a, string b)
{
          return a.size()<b.size();
}
int main()
{
#if defined(_DEBUG)
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
 press_F_to_pay_respect;
 int x;
 cin>>x;
 ll ans=0;
 int j=x/500;
 x-=j*500;
 ans+=j*1000;
 j=x/5;
 ans+=j*5;
 cout<<ans;
 
 
 
 
  // cout <<"Runtime is:"<<clock() * 1.0 / CLOCKS_PER_SEC <<endl;
   return 0;
   
   

}

Measured memory_bytes: 256
/*
    _____
  .'|||||'.
 /  >   <  \
|     ^     |
|  \     /  |
 \  '---'  /
  '._____.'
    |||||
*/

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
#include<queue>
using namespace std;
#define CL(x,v); memset(x,v,sizeof(x));
#define INF 0x3f3f3f3f
#define LL long long
#define REP(i,r,n) for(int i=r;i<=n;i++)
#define RREP(i,n,r) for(int i=n;i>=r;i--)

int main()
{
    int n,d;
    scanf("%d%d",&n,&d);
    if (n%(2*d+1)==0) printf("%d\n",n/(2*d+1)); else
        printf("%d\n",n/(2*d+1)+1);
    return(0);
}


Measured memory_bytes: 256
import java.util.*

fun main(args: Array<String>) {
    val sc = Scanner(System.`in`)
    val s = sc.next()
    println(problem120c(s))
}

fun problem120c(s: String): Int {
    var redCount = 0
    var blueCount = 0
    for (i in s.indices) {
        when (s[i]) {
            '0' -> redCount++
            '1' -> blueCount++
            else -> {}
        }
    }
    if (redCount == 0 || blueCount == 0) return s.length - Math.max(redCount, blueCount)
    return s.length - (Math.max(redCount, blueCount) - Math.min(redCount, blueCount))
}

Measured memory_bytes: 34392
#include<iostream>
#include<cstdio>
#include<cstring>
int f(int a,int b,int c)
{
	int ret=0;
	while(a%2==b%2 && b%2==c%2)ret++,a>>=1,b>>=1,c>>=1;
	return ret;
}
void solve()
{
	int x,y,z;
	scanf("%d%d%d",&x,&y,&z);
	if(x%2 || y%2 || z%2)printf("0\n");
	else if(x==y && y==z)printf("-1\n");
	else printf("%d\n",f(x,y,z));
}
int main()
{
	solve();
	return 0;
}


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

using namespace std;

vector<vector<int>> que;
int n,m;

long long check(vector<int> v){
	long long ret=0;

	for(auto a:que){
		if(v.at(a.at(1)-1)-v.at(a.at(0)-1)==a.at(2)) ret+=a.at(3);
	}

	return ret;
}

long long solve(vector<int> v,int p){
	bool end=false;
	for(int i=1;i<v.size();i++){
		if(v.at(i)<v.at(i-1)){
			end=true;
			break;
		}
	}
	if(end) return 0;
	if(p<0) return 0;

	long long ret=check(v);

	for(int i=v.at(p);i<m;i++){
		v.at(p)++;
		ret=max(ret,solve(v,p-1));
	}

	return ret;
}

int main(){
	int q;
	cin>>n>>m>>q;
	vector<int> hoge(4);
	for(int i=0;i<q;i++){
		cin>>hoge.at(0)>>hoge.at(1)>>hoge.at(2)>>hoge.at(3);
		que.push_back(hoge);
	}

	vector<int> fuga(n,1);

	cout<<solve(fuga,n-1)<<endl;;

	return 0;
}


Measured memory_bytes: 3612
import math
N = int(input())
x = [0] * N
y = [0] * N
for i in range(N):
    x[i], y[i] = map(int, input().split())

D = [[0] * N for _ in range(N)]
S = 0
for i in range(N-1):
    for j in range(i+1, N):
        S += math.sqrt((x[i]-x[j])**2 + (y[i]-y[j])**2)


print(S*2/N)

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

int main() {
    int N, K; cin >> N >> K;
    vector<int> p;
    vector<int> m;
    rep(i, N){
        int x; cin >> x;
        if(x < 0){
            m.push_back(-x);
        } else {
            p.push_back(x);
        }
    }

    int ans = 1001001001;
    int psize = p.size();
    int msize = m.size();
    for (int i = 0; i <= msize; i++){
        int pnum = K-i;
        if(pnum > psize || pnum < 0)continue;
        int left, right;
        if(i == 0){
            left = 0;
        } else {
            left = m[msize-i];
        }
        if(pnum == 0){
            right = 0;
        } else {
            right = p[pnum-1];
        }
        int now = min(left*2+right, left+right*2);
        ans = min(ans, now);
    }

    cout << ans << endl;


    return 0;
}

Measured memory_bytes: 3976
#include<stdio.h>
void init(void);

int l[200],r[200];

int main(void){
    char s[200];
    int i,n,d,cnt,max=0;
    scanf("%d",&n);
    scanf("%s",s);
    for(d=0;d<n;d++){
        init();
        cnt=0;
        for(i=0;i<d;i++){
            l[s[i]]=1;
        }
        for(i=d;i<n;i++){
            r[s[i]]=1;
        }
        for(i=0;i<200;i++){
            if(l[i]==1&&r[i]==1){
                cnt++;
            }
        }
        if(cnt>max){
            max=cnt;
        }
    }
    printf("%d\n",max);
    return 0;
}

void init(void){
    int i;
    for(i=0;i<200;i++){
        l[i]=0;
        r[i]=0;
    }
    return;
}


Measured memory_bytes: 128
#include<iostream>
#define _USE_MATH_DEFINES
#include<math.h>
using namespace std;
struct Point {
	double x, y;
};
int koch(Point p1,Point p2,int n);


int main() {
	int n;
	Point p1 = { 0,0 }, p2 = {100,0};
	cin >> n;
	cout << p1.x << " " << p1.y << endl;
	koch(p1,p2, n);
	cout << p2.x << " " << p2.y << endl;
	return 0;
}

int koch(Point p1, Point p2, int n) {
	Point u,s,t;
	double th;
	s.x = (2 * p1.x + p2.x) / 3.0;
	s.y = (2 * p1.y + p2.y) / 3.0;
	t.x = (p1.x + 2 * p2.x) / 3.0;
	t.y = (p1.y + 2 * p2.y) / 3.0;
	th = M_PI / 3.0;
	u.x = (t.x - s.x) * cos(th) - (t.y - s.y) * sin(th) + s.x;
	u.y = s.y + (t.x - s.x) * sin(th) +(t.y- s.y) * cos(th);
	if (n == 0){ 
		return 0;
	}
	else {
		koch(p1, s, n - 1);
		cout << s.x << " " << s.y << endl;
		koch(s,u, n - 1);
		cout << u.x << " " << u.y << endl;
		koch(u,t, n - 1);
		cout << t.x << " " << t.y << endl;
		koch(t,p2 ,n - 1);
	}
}

Measured memory_bytes: 1256
#include <cstdio>
#include <algorithm>
using namespace std;
const long long INF = (long long) 1 << 62;
long long G[107][107];
int main() {
    int v, e;
    scanf("%d%d", &v, &e);
    for (int i = 0; i < v; i++) {
    	for (int j = 0; j < v; j++) {
    		if (i != j) G[i][j] = INF;
		}
	}
	for (int i = 0; i < e; i++) {
		int from, to, w;
		scanf("%d%d%d", &from, &to, &w);
		G[from][to] = w;
	}
	for (int k = 0; k < v; k++) {
		for (int i = 0; i < v; i++) {
			for (int j = 0; j < v; j++) {
				if (G[i][k] < INF && G[k][j] < INF) G[i][j] = min(G[i][j], G[i][k] + G[k][j]);
			}
		}
	}
	for (int i = 0; i < v; i++) {
		if (G[i][i] < 0) {
			printf("NEGATIVE CYCLE\n");
			return 0;
		}
	}
	for (int i = 0; i < v; i++) {
		if (G[i][0] >= INF) printf("INF");
    	else printf("%lld", G[i][0]);
    	for (int j = 1; j < v; j++) {
    		if (G[i][j] >= INF) printf(" INF");
    		else printf(" %lld", G[i][j]);
		}
		putchar('\n');
	}
	return 0;
}


Measured memory_bytes: 2828
module Main where
import Data.List(zipWith)
int = read :: String -> Int
replace pred a = map (\x -> if pred x then a else x)
main = interact $ printer . solver . parser
parser = map (map int . words) . lines
printer = unlines . (:[]) . show

solver :: [[Int]] -> Int
solver [ns,a1,a2] = last b2 
  where
    n = head ns :: Int
    b1 = scanl1 (+) a1 :: [Int]
    b2 = tail $ scanl (\n (b,a)-> a + max n b) 0 $ zip b1 a2 :: [Int]

Measured memory_bytes: 1020
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<cmath>
#include<map>
#include<iomanip>
#include<queue>
#include<stack>
#include<time.h>
#define rep(i,n)for(int i=0;i<n;i++)
#define int long long
#define ggr getchar();getchar();return 0;
#define prique priority_queue
#define mod 1000000007
#define inf 1e15
#define double long double
using namespace std;
typedef pair<int, int>P;
void pyes() { cout << "Yay!" << endl; }
void pno() { cout << ":(" << endl; }
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x % y);
}
int lcm(int x, int y) {
	return x / gcd(x, y) * y;
}
int kai(int x, int y) {
	int res = 1;
	for (int i = x - y + 1; i <= x; i++) {
		res *= i; res %= mod;
	}
	return res;
}
//繰り返し二乗法
int mod_pow(int x, int y, int m) {
	int res = 1;
	while (y) {
		if (y & 1) {
			res = res * x % m;
		}
		x = x * x % m;
		y >>= 1;
	}
	return res;
}
//xCy
int comb(int x, int y) {
	if (y > x)return 0;
	return kai(x, y)* mod_pow(kai(y, y), mod - 2, mod) % mod;
}
int f(int x) {
	int ans = 1;
	for (int i = 1; i <= x; i++) {
		ans *= i;
		ans %= mod;
	}
	return ans;
}
struct edge { int to, cost; };
signed main() {
	int a, b, c, d;
	cin >> a >> b >> c >> d;
	if (d == 1)cout << 1 << endl;
	else cout << 0 << endl;
	ggr
}


Measured memory_bytes: 256
import java.util.Scanner;
public class Main{
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		int a[]=new int[n];
		int sum=0;
		for(int i=0;i<n;i++) {
			a[i]=sc.nextInt();
			sum+=a[i];
		}
		//int b[][]=new int[n][n];
		int ans=0;
		for(int i=0;i<n;i++) {
			ans+=a[i]*(sum-a[i]);
		}
		System.out.println(ans/2);

	}
}


Measured memory_bytes: 22228
#include <iostream>
#include <numeric>
#include <iomanip>
#include <string> // string, to_string, stoi
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)




int main() {


	int H, W;
	cin >> H >> W;
	string s;
	char d;
	int p;
	rep(i, H) {
		rep(j, W) {
			cin >> s;
			if (s == "snuke") {
				 d = 'A' + j;
				 p = i;
				
			}
		}
	}
	cout << d << p + 1 << endl;
}

Measured memory_bytes: 256
fun main(args: Array<String>) {
    val card = Array(3) {
        readLine()!!.split(" ").map(String::toInt)
    }
    val N = readLine()!!.toInt()
    val list = Array(N) {
        readLine()!!.toInt()
    }
    val score = Array(3) {
        BooleanArray(3)
    }
    for (i in list.indices) {
        val n = list[i]
        for (j in card.indices) {
            if (n == card[j][0]) {
                score[j][0] = true
            }
            if (n == card[j][1]) {
                score[j][1] = true
            }
            if (n == card[j][2]) {
                score[j][2] = true
            }
        }
    }
    if ((score[0][0] && score[0][1] && score[0][2])
        || (score[1][0] && score[1][1] && score[1][2])
        || (score[2][0] && score[2][1] && score[2][2])
        || (score[0][0] && score[1][0] && score[2][0])
        || (score[0][1] && score[1][1] && score[2][1])
        || (score[0][2] && score[1][2] && score[2][2])
        || (score[0][0] && score[1][1] && score[2][2])
        || (score[0][2] && score[1][1] && score[2][0])
    ) {
        println("Yes")
    } else {
        println("No")
    }
}

Measured memory_bytes: 37608
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 標準入力からデータを読み込む準備
try (Scanner sc = new Scanner(System.in)) {
while (true) {
int n = sc.nextInt();
if (n == 0) { break; }
int[] scores = new int[n];
for (int i = 0; i < scores.length; i++) {
scores[i] = sc.nextInt();
}
double average = 0, variance = 0;
// … 平均値averageと，分散varianceを計算しよう …
for(int i=0;i<scores.length;i++)average+=scores[i];
average/=n;
for(int i=0;i<scores.length;i++){
    variance+=Math.pow(scores[i]-average,2);
}
variance/=n;
System.out.println(Math.sqrt(variance));
}
}
}
}


Measured memory_bytes: 31504
let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let s = read_line () |> split_string |> Array.of_list
let k = Scanf.sscanf (read_line ()) "%d" @@ fun k -> k

let s_len = Array.length s

let f () = 
  let cnt = Array.of_list @@ fst @@ Array.fold_left (fun (acc, before) ch ->
    match acc with
      | [] -> ([1], ch)
      | x :: xs -> ((if before = ch then ((x + 1) :: xs) else 1 :: acc), ch)
  ) ([], "") s in
  if Array.length cnt = 1 then s_len * k / 2
  else
  (cnt |> Array.map (fun i -> i / 2) |> Array.fold_left (+) 0) * k -
    if s.(0) = s.(s_len - 1) then let a, b = cnt.(0), cnt.(Array.length cnt - 1) in (a / 2 + b / 2 - (a + b) / 2) * (k - 1)
    else 0

let () =
  Printf.printf "%d\n" @@ match s_len with
    | 1 -> k / 2
    | 2 -> if s.(0) = s.(1) then k else 0
    | _ -> f ()


Measured memory_bytes: 2432
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

def edges_to_pt(s,t,n,directed=False):
    pt = [[] for _ in range(n)]
    for i in range(len(s)):
        pt[s[i]-1].append(t[i]-1)
        if directed == False:
            pt[t[i]-1].append(s[i]-1)
    return pt

def tree_diameter(pt):
    def bfs(pt,v):
        n = len(pt)
        visited = [False]*n
        visited[v] = True
        max_d = 0
        max_d_index = v
        q = [v]
        c = 1
        while q:
            q1 = []
            for i in q:
                for j in pt[i]:
                    if not visited[j]:
                        visited[j] = c
                        max_d = c
                        max_d_index = j
                        q1.append(j)
            q = q1
            c += 1
        return max_d, max_d_index
    
    _,index = bfs(pt,0)
    return bfs(pt,index)[0]

N = I()
a,b = LIR(N-1,2)

pt = edges_to_pt(a,b,N)
r = tree_diameter(pt)

# 木の直径 r（≥2）を -1 or -2 できる
# r = 1 をもらうと負け
if r%3 == 1:
    print('Second')
else:
    print('First')

Measured memory_bytes: 121680
#include<bits/stdc++.h>
#define ll long long
#define pb push_back
#define po pop_back
#define fi first
#define se second
#define hello ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define MOD 998244353  
using namespace std;
bool comp(ll a,ll b){if(a>b)return true;else return false;}
int isP(ll n){if(n==1)return 0;if(n==2 || n==3)return 1;for(ll i=2;i<=sqrt(n);i++){if(n%i==0)return 0;}return 1;}
ll power(ll a,ll b){if(b==0)return 1;if(b==1) return a;ll t=power(a,b/2);if(b%2==1) return t*t*a;else return t*t;}
ll powMOD(ll x,ll y){if(y==0)return 1;if(y==1)return x;ll t=powMOD(x,y/2);if(y%2==1)return t*t%MOD*x%MOD;else return t*t%MOD;}
bool cmp(pair<ll,ll> p1,pair<ll,ll> p2){if(p1.fi>p2.fi) return true;if(p1.fi==p2.fi && p1.se>p2.se) return true;return false;}

int main()
{
    hello;
    
    ll t; 
//    cin>>t;
	t=1;
	
	while(t--){
		ll n,x,m;
		cin>>n>>x>>m;
		bool hai[m]={};
		for(ll i=0;i<m;i++){
			if(i*i%m==0) hai[i]=1;
		}
		bool hogya[m]={};
		ll ans=0;
		ll cnt=0;
		ll ho[m]={};
		ll cn[m]={};
		while(cnt<n){
			if(hai[x]){
				ans+=x;
				break;
			}
			if(hogya[x]){
				ll val=ans-ho[x];
				ll l=n-cnt;
				ll le=l/(cnt-cn[x]);
				ans+=le*val;
				l-=le*(cnt-cn[x]);
				for(ll i=1;i<=l;i++){
					ans+=x;
					x=x*x%m;
				}
				break;
			}
			ho[x]=ans;
			cn[x]=cnt;
			hogya[x]=1;
			cnt++;
			ans+=x;
			x=x*x%m;
		}
		cout<<ans<<"\n";
	}
    
    return 0;  
}

Measured memory_bytes: 5288
#include <bits/stdc++.h>
using namespace std;
#define rep(i,N) for(int i=0,i##_max=(N);i<i##_max;++i)
#define repp(i,l,r) for(int i=(l),i##_max=(r);i<i##_max;++i)
#define per(i,N) for(int i=(N)-1;i>=0;--i)
#define perr(i,l,r) for(int i=r-1,i##_min(l);i>=i##_min;--i)
#define all(arr) (arr).begin(), (arr).end()
#define SP << " " <<
#define SPF << " "
#define SPEEDUP cin.tie(0);ios::sync_with_stdio(false);
#define MAX_I INT_MAX //1e9
#define MIN_I INT_MIN //-1e9
#define MAX_UI UINT_MAX //1e9
#define MAX_LL LLONG_MAX //1e18
#define MIN_LL LLONG_MIN //-1e18
#define MAX_ULL ULLONG_MAX //1e19
  typedef long long ll;
  typedef pair<int,int> PII;
  typedef pair<char,char> PCC;
  typedef pair<ll,ll> PLL;
  typedef pair<char,int> PCI;
  typedef pair<int,char> PIC;
  typedef pair<ll,int> PLI;
  typedef pair<int,ll> PIL; 
  typedef pair<ll,char> PLC; 
  typedef pair<char,ll> PCL; 

inline void YesNo(bool b){ cout << (b?"Yes" : "No") << endl;}
inline void YESNO(bool b){ cout << (b?"YES" : "NO") << endl;}
inline void Yay(bool b){ cout << (b?"Yay!" : ":(") << endl;}

int main(void){
  SPEEDUP
  cout << setprecision(15);
  int N;ll K;cin >> N >> K;
  vector<ll> A(N);
  vector<ll> F(N);
  rep(i,N)cin >> A[i];
  rep(i,N)cin >> F[i];
  //積がfitst,自分の数値がi
  priority_queue<PLL> pque;
  sort(all(A));
  sort(all(F),greater<ll>());
  //成績
  ll s = -1, e = 1e12;
  while(e-s>1){
    //解をX以下にできるか．
    ll X = (s+e)/2;
    bool issat = true;
    ll k = K;
    rep(i,N){
      ll Q = X/F[i];
      k -= max(0ll,A[i]-Q);
      if(k<0){
        issat = false;
        break;
      }
    }
    if(issat) e = X;
    else s = X;
  }
  cout << e << endl;
  return 0;
}


Measured memory_bytes: 3456
N=int(input())
S=str(input())
result=0

for i in range(1,N):
	valiation=0
	A=sorted(S[:i])
	B=sorted(S[i:])
	for j in range(i):
		if (j==0 or A[j]!=A[j-1]) and A[j] in B:
			valiation+=1
	result=max(result,valiation)
print(result)


Measured memory_bytes: 3060
#include<cstdio>
using namespace std;
#define N 10050
int n,k,tp;
char s[N],t[N],as[N],as1[N];
void solve()
{
	int le=0,st=n;
	while(t[st]==t[n])le++,st--;
	le<<=(k-1);
	if(le>n)le=n;
	for(int i=1;i<=le;i++)as1[i]=t[n];
	for(int i=le+1,k=st;i<=n;i++,k--)as1[i]=t[k];
	for(int i=1;i<=n;i++)if(as[i]>as1[i]){for(int j=1;j<=n;j++)as[j]=as1[j];return;}
	else if(as[i]<as1[i])return;
}
int main()
{
	scanf("%d%d%s",&n,&k,s+1);
	if(k>=14){char as='z';for(int i=1;i<=n;i++)if(s[i]<as)as=s[i];for(int i=1;i<=n;i++)printf("%c",as);return 0;}
	tp=1<<k-1;
	for(int i=1;i<=n;i++)s[n*2-i+1]=s[i];
	as[1]='z'+1;
	for(int i=n+1;i<=n*2;i++)
	{
		for(int j=i-n+1;j<=i;j++)t[j-i+n]=s[j];
		solve();
	}
	printf("%s",as+1);
}

Measured memory_bytes: 256
#include<algorithm>
#include<cstring>
#include<cstdio>
#define LL long long
#define Re register int
using namespace std;
const int N=2e5+3;
int n,t,A[N],L[N],R[N],Q[N];LL ans;
inline void in(Re &x){
    int f=0;x=0;char c=getchar();
    while(c<'0'||c>'9')f|=c=='-',c=getchar();
    while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^48),c=getchar();
    x=f?-x:x;
}
int main(){
//	freopen("123.txt","r",stdin);
	in(n);
	for(Re i=1;i<=n;++i)in(A[i]);
	for(Re i=1;i<=n;++i){
		while(t&&A[Q[t]]>=A[i])--t;
		L[i]=Q[t]+1,Q[++t]=i;
	}
	Q[t=0]=n+1;
	for(Re i=n;i>=1;--i){
		while(t&&A[Q[t]]>=A[i])--t;
		R[i]=Q[t]-1,Q[++t]=i;
	}
	for(Re i=1;i<=n;++i)ans+=(LL)A[i]*(R[i]-i+1)*(i-L[i]+1);
	printf("%lld\n",ans);
}

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

#define v_max 100000
#define n_max 100

vector<vector<ll>> dp(v_max+1, vector<ll>(n_max, 0));
bool vis[v_max+1][n_max];

ll solve(ll val, ll i, vector<ll>& w, vector<ll>& v){
	if(val<=0)
		return 0;
	if(i==w.size())
		return 1e9;
	if(vis[val][i])
		return dp[val][i];
	vis[val][i] = true;
	dp[val][i] = min(solve(val, i+1, w, v), w[i]+solve(val-v[i], i+1, w, v));
	return dp[val][i];
}
ll func(vector<ll>& w, vector<ll>& v, ll W, ll sum){
	for(ll i=sum;i>=0;i--){
		if(solve(i, 0, w, v)<=W)
			return i;
	}
	return 0;
}
int main(){
	ll n, W;
	cin>>n>>W;
	vector<ll> w(n);
	vector<ll> v(n);
	ll i,j;
	ll sum=0;
	for(i=0;i<n;i++){
		cin>>w[i]>>v[i];
		sum+=v[i];
	}
	dp.resize(sum);
	ll ans = func(w, v, W, sum);
	cout<<ans<<"\n";
	return 0;
}

Measured memory_bytes: 94940
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <utility>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#define rep(i, n) for(int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
ll mod = 1000000007;
 
int main() {
    int r;
    cin >> r;
    cout << 3*r*r;
    
    cout << endl;
    return 0;
}

Measured memory_bytes: 256
import sys

def main():
    N, Y = map(int, sys.stdin.readline().rstrip().split())

    for n in range(Y//10000+1):
        for m in range((Y-n*10000)//5000+1):
            l = N - n - m
            if l >= 0 and n*10000 + m*5000 + l*1000 == Y:
                print(n, m, l)
                return
    
    print(-1, -1, -1)


if __name__ == '__main__':
    main()

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

int c;
c = sc.nextInt();

int d = 1;

if(a>b) {
d = a;
a = b;
b = d;
}

if(b>c) {
d = b;
b = c;
c = d;
}

if(a>b) {
d = a;
a = b;
b = d;
}

System.out.println(a+" "+b+" "+c);
}
}



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

int main(){
  int n;
  cin >> n;
  vector<long> a(n);
  for(int i=0;i < n;i++){
    cin >> a.at(i);
  }
  long long ans = 0;
  for(int i=1;i < n;i++){
    if(a.at(i) < a.at(i-1)){
      ans += a.at(i-1) - a.at(i);
      a.at(i) = a.at(i-1);
    }
  }
  cout << ans << endl;
}

Measured memory_bytes: 4840
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<vector>
#include<cmath>
#include<cstdio>
#include<complex>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define it ::iterator
#define all(in) in.begin(),in.end()
const double PI=acos(-1);
const double EPS=1e-10;
using namespace std;
typedef complex<double> P;
P pin(){
	double x,y;
	cin>>x>>y;
	P p(x,y);
	return p;
}
void PIN(P* a,int i){
	rep(i,2)a[i]=pin();
}
double dot(P a,P b){
	return real(conj(a)*b);
}
double cross(P a,P b){
	return imag(conj(a)*b);
}
string s[5]={"COUNTER_CLOCKWISE","CLOCKWISE","ONLINE_BACK","ONLINE_FRONT","ON_SEGMENT"};
int main(){
	P a[2];
	PIN(a,2);
	int n;
	cin>>n;
	rep(i,n){
		P p=pin();
		P b=a[1]-a[0];
		P c=p-a[0];
		int ans;
		if(cross(b,c)<0)ans=1;
		else if(cross(b,c)>0)ans=0;
		else if(dot(b,c)<0)ans=2;
		else if(abs(b)<abs(c))ans=3;
		else ans=4;
		cout<<s[ans]<<endl;
	}
}

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

int main() {
  int a,b;
  cin >> a >> b;
    
    if ( a/2 == (a-1)/2 && b/2 == (b-1)/2 ) {
      cout << "Odd" << endl;
    }
  else {
    cout << "Even" << endl;
  }
}


Measured memory_bytes: 3584
// =====================================================================
// macros
// =====================================================================

/// stdin macro from https://techracho.bpsinc.jp/jhonda/2019_08_05/78537
macro_rules! stdin {
    () => {{
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s).unwrap();
        s
    }};
}

/// input macro from https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

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

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

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

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

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

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

/// test macro from https://techracho.bpsinc.jp/jhonda/2019_08_05/78537
macro_rules! test {
    ($($input:expr => $output:expr),* $(,)*) => {
        #[test]
        fn answer_test() {
            $(
                assert_eq!(answer($input), $output);
            )*
        }
    };
}
// =====================================================================
// test cases
// =====================================================================

test!{
    /// write inputs for test cases here.
    /// e.g.) 
    /// ```
    /// "1 2 3"=>"4",
    /// r"4 5 6
    ///   7 8 9"=>"10",
    /// ```
    r"2 3 3"=>"0 2",
}

// =====================================================================
// functions
// =====================================================================

/// answer fn for the problem
fn answer(input: &str)->String{
    input!{
        source = input,
        a: usize,
        b: usize,
        k: usize,
    }
    if a>k {
        a -= k;
    }else{
        k -= a;
        a = 0;
        if b > k {
            b -= k;
        }else{
            b = 0;
        }
    }
    let result = a.to_string() + " " + &b.to_string();
    return result.to_string();
}

/// the entry point
fn main() {
    println!("{}",answer(&stdin!()));
}


Measured memory_bytes: 4352
//ヘッダー
#include<bits/stdc++.h>
using namespace std;

//型定義
typedef long long ll;

//定数
const int INF=1e+9;
const int MOD=1e+9+7;

//REPマクロ
#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define REP2(i,a,b) for(ll i=a;i<(ll)(b);i++)
#define REPD2(i,a,b) for(ll i=a;i>(ll)(b);i--)

// 多次元 vector 生成
template<class T>
vector<T> make_vec(size_t a){
    return vector<T>(a);
}
template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

//vectorの扱い
#define ALL(x) (x).begin(),(x).end() //sortなどの引数省略
#define SIZE(x) ((ll)(x).size()) //size
#define MAX(x) *max_element(ALL(x)) //最大値
#define MIN(x) *min_element(ALL(x)) //最小値

const ll NMAX=100100;
using vll=vector<vector<ll>>;
using vl=vector<ll>;

vll G(NMAX);
vl deep(NMAX,-1);

ll dfs(ll v){
    if(deep[v]!=-1) return deep[v];
    
    ll Gs=G[v].size();
    ll res=Gs;

    priority_queue<ll> que;
    for(auto nv:G[v]){
        que.push(dfs(nv));
    }

    REP(i,Gs){
        ll n=que.top();
        que.pop();
        res=max(i+1+n,res);
    }

    return deep[v]=res;
}

int main(){
    ll N;
    cin>>N;
    vector<ll> a(N-1);
    REP(i,N-1){
        cin>>a[i];
        a[i]--;
        G[a[i]].push_back(i+1);
    }
    cout<<dfs(0)<<endl;

}

Measured memory_bytes: 22708
#include<bits/stdc++.h>
#define Fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;

int main()
{
    Fast;
    long long t,n,m,i,j,k,x=0,y=0,z;
    cin>>n;
    cout<<(n+1)/2<<endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
  os << "(" << p.first << "," << p.second << ")";
  return os;
}
#ifdef __LOCAL
#define debug(x) cerr << __LINE__ << ": " << #x << " = " << (x) << endl
#define debugArray(x, n)                                      \
  cerr << __LINE__ << ": " << #x << " = {";                   \
  for (long long hoge = 0; (hoge) < (long long)(n); ++(hoge)) \
    cerr << ((hoge) ? "," : "") << x[hoge];                   \
  cerr << "}" << endl
#else
#define debug(x) (void(0))
#define debugArray(x, n) (void(0))
#endif

signed main() {
  cin.tie(0);
  ios::sync_with_stdio(0);
  int N;
  cin >> N;
  int P[N * N];
  for (int i = 0; i < N * N; i++) cin >> P[i], P[i]--;
  auto node = [&](int i, int j) { return N * i + j; };
  auto ij = [&](int v) { return make_pair(v / N, v % N); };
  pair<int, int> dir[4] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
  int cost[N * N];
  for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
      cost[node(i, j)] = min({i + 1, N - i, j + 1, N - j});
    }
  }
  bool rem[N * N];
  fill(rem, rem + N * N, true);
  // debugArray(cost, N * N);
  int ans = 0;
  for (int p : P) {
    rem[p] = false;
    queue<pair<int, int>> que;
    que.push({p, cost[p] - 1});
    while (!que.empty()) {
      int v, c;
      tie(v, c) = que.front();
      que.pop();
      if (cost[v] <= c) continue;
      cost[v] = c;
      int ci, cj;
      tie(ci, cj) = ij(v);
      for (int d = 0; d < 4; d++) {
        int ni = ci + dir[d].first, nj = cj + dir[d].second;
        if (ni < 0 || N <= ni || nj < 0 || N <= nj) continue;
        int next = node(ni, nj);
        if (cost[next] > cost[v] + rem[next])
          que.push({next, cost[v] + rem[next]});
      }
    }
    ans += cost[p];
    // debugArray(cost, N * N);
  }

  cout << ans << '\n';
  return 0;
}


Measured memory_bytes: 5808
/* -------------------------------- Template -------------------------------- */

#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <locale>
#include <iostream>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define ALL(x) (x).begin(),(x).end()

using ll = long long;
using ld = long double;

template <typename T> T &chmin(T &a, const T &b) { return a = std::min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = std::max(a, b); }
template <typename T> int len(const T &x) { return x.size(); }

// template<typename T> constexpr T inf = [](){ assert(false); };
// template<> constexpr int inf<int> = 1e9;
// template<> constexpr ll inf<ll> = 1e18;
// template<> constexpr ld inf<ld> = 1e30;

struct yes_no : std::numpunct<char> {
  string_type do_truename()  const { return "Yes"; }
  string_type do_falsename() const { return "No"; }
};

void solve();

int main() {
  std::locale loc(std::locale(), new yes_no);
  std::cout << std::boolalpha << std::setprecision(12) << std::fixed;
  std::cout.imbue(loc);
  solve();
  return 0;
}

using namespace std;

/* -------------------------------- Library -------------------------------- */

/* ---------------------------------- Main ---------------------------------- */

int A[128000], B[128000];

void solve() {
  int N, Q;
  cin >> N >> Q;
  A[1] = 1;
  B[1] = 1;
  B[2] = 1;
  int p = 1;
  REP(i,Q) {
    int L, R;
    cin >> L >> R;
    swap(A[L], A[R]);
    swap(B[L], B[R]);
    if (A[L]) p = L;
    if (A[R]) p = R;
    B[p-1] = 1;
    B[p+1] = 1;
  }
  cout << accumulate(B + 1, B + N + 1, 0) << endl;
  return;
}


Measured memory_bytes: 1024
S = input()

cntB = 0
cntW = 0
ans = 0

idx = 0

while idx < len(S):
    #print(idx,cntB,cntW,ans)
    if S[idx] == 'B':
        cntB += 1
        idx += 1
    else:
        while idx < len(S):
            if S[idx] == 'W':
                cntW += 1
                idx += 1
                #print(idx,cntW)
            else:
                ans += cntB*cntW
                cntW = 0
                break
        ans += cntB*cntW
        
print(ans)

Measured memory_bytes: 3500
#include<iostream>
#include<set>
#include<map>
#include<unordered_set>
#include<cmath>
#include<algorithm>
using namespace std;
#include<vector>
#define int long long int
int32_t main()
{
	int n,k;
	cin>>n>>k;
	bool dp[k+1]={false};
	int j;
	int arr[n];
	for(j=0;j<n;j++)
	{
		cin>>arr[j];
	}
	int minval=arr[0];
	for(j=1;j<n;j++)
	{
		minval=min(minval,arr[j]);
	}
	dp[minval]=true;
	for(j=minval+1;j<=k;j++)
	{
		bool result=false;
		for(int i=0;i<n;i++)
		{
			if(j-arr[i]>=0)
			{
				if(j-arr[i]==0)
				{
					result=true;
				}
				else
				{
					if(!dp[j-arr[i]])
				    {
						result=true;
					}
				}
			}
		}
		dp[j]=result;
	}
	if(dp[k])
	{
		cout<<"First"<<endl;
	}
	else
	   cout<<"Second"<<endl;
}



Measured memory_bytes: 3700
#include <stdio.h>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;




int main()
{
    long long n;scanf("%lld",&n);
    if (n%2) printf("0\n");
    else{
        long long ans=0;
        //for (long long i=10;i<=n;i*=10)
        //    ans+=1LL*n/i;
        n/=2;
        while (n){
            ans+=n/(1LL*5);
            n/=5;
        }
        printf("%lld\n",ans);
    }

}


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

using namespace std;

#define INF 1000000007
#define int long long
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define rep(i, n) FOR(i, 0, n)
#define maxn 100005

signed main()
{
    int N;
    cin >> N;
    int A[N + 1], B[N + 1], C[N];
    for (int i = 1; i <= N; i++)
    {
        cin >> A[i];
    }

    for (int i = 1; i <= N; i++)
    {
        cin >> B[i];
    }

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

        cin >> C[i];
    }
    int ans = 0;
    for (int i = 1; i <= N; i++)
    {
        ans += B[i];
        if (i > 1)
        {
            if (A[i - 1] + 1 == A[i])
            {
                ans += C[A[i - 1]];
            }
        }
    }
    cout << ans << endl;
    ;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<stack>
#include<climits>
#include<cmath>

int main(){
	std::string s;
	std::cin>>s;

	if(s[5]-'0'>= 1 || s[6]-'0'>=5)
		std::cout<< "TBD"<<std::endl;
	else
		std::cout<< "Heisei"<<std::endl;

	return 0;
}

Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
            var H = a[0];
            var N = a[1];
            var A = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);

            if (H <= A.Sum())
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        }
    }
}


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

#if defined(__unix__) || defined(__APPLE__)

#include <sys/resource.h>

#endif
#define p 1000000007

using namespace std;

long long solve(vector<vector<long long>> &dp, vector<long long> &a, int k) {
    for (int i = 0; i < dp.size(); i++) {
        dp[i][0] = 1;
    }
    for (int i = 0; i < dp[0].size(); i++) {
        dp[0][i] = (i <= a[0] ? 1 : 0);
    }
    long long prefixSum[k + 1];

    for (int i = 1; i < dp.size(); i++) {
        prefixSum[0] = dp[i - 1][0];
        for (int q = 1; q <= k; q++)
            prefixSum[q] = (dp[i - 1][q] + prefixSum[q - 1]) % p;
        for (int j = 1; j < dp[i].size(); j++) {
            long long l = max((long long) j - a[i], (long long) 0), r = j;
            dp[i][j] = (p + (prefixSum[r]) - (l == 0 ? 0 : prefixSum[l - 1])) % p;
        }
    }
    return dp[dp.size() - 1][k];
}


int main_with_large_stack_space() {
    ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    vector<vector<long long> > dp(n);
    vector<long long> a(n);
    for (int j = 0; j < n; ++j) {
        cin >> a[j];
    }
    for (int i = 0; i < n; i++)
        for (int j = 0; j <= k; j++)
            dp[i].push_back(0);
    cout << solve(dp, a, k);
    return 0;

}

int main(int argc, char **argv) {
#if defined(__unix__) || defined(__APPLE__)
    const rlim_t kStackSize = 1024 * 1024 * 1024;
    struct rlimit rl;
    int result;

    result = getrlimit(RLIMIT_STACK, &rl);
    if (result == 0) {
        if (rl.rlim_cur < kStackSize) {
            rl.rlim_cur = kStackSize;
            result = setrlimit(RLIMIT_STACK, &rl);
            if (result != 0) {
                cerr << "setrlimit returned result = " << result << endl;
            }
        }
    }

#endif
    return main_with_large_stack_space();
}

Measured memory_bytes: 79604