akhauriyash/Code-Regression huggingface dataset:
#include <stdio.h>
#include <stdlib.h>

int assort(const void *a, const void *b){return *(long long*)a-*(long long*)b;}
int dessort(const void *a, const void *b){return *(long long*)b-*(long long*)a;}

int main(void){
    int n;
    scanf("%d",&n);
    long long a[300030],ar[n+1],al[n+1],tmp,R[100005]={},L[100005]={};
    ar[0]=-1;
    al[0]=10e10;
    for (int i=0; i<n*3; i++){
        scanf("%lld",&a[i]);
    }
    
    if (n==1){
        tmp=a[0]-a[1];
        tmp=tmp>(a[1]-a[2])?tmp:(a[1]-a[2]);
        tmp=tmp>(a[0]-a[2])?tmp:(a[0]-a[2]);
        printf("%lld\n",tmp);
        return 0;
    }
    
    for (int i=0; i<n; i++){
        ar[i+1]=a[i];
        R[0]+=ar[i+1];
    }
    qsort (ar,n+1,sizeof(long long),assort);
    for (int i=0; i<n; i++){
        tmp=a[i+n];
        if (tmp>ar[1]){
            R[i+1]=R[i]-ar[1]+tmp;
            ar[1]=tmp;
            long long bf=1;
            while(1){
                if (bf*2>n){
                    break;
                }
                if (ar[bf*2]<=ar[bf*2+1] || bf*2+1>n){
                    if (ar[bf]>ar[bf*2]){
                        tmp=ar[bf];
                        ar[bf]=ar[bf*2];
                        ar[bf*2]=tmp;
                        bf=bf*2;
                    } else {
                        break;
                    }
                } else {
                    if (ar[bf]>ar[bf*2+1]){
                        tmp=ar[bf];
                        ar[bf]=ar[bf*2+1];
                        ar[bf*2+1]=tmp;
                        bf=bf*2+1;
                    } else {
                        break;
                    }
                }
            }
        } else {
            R[i+1]=R[i];
        }
    }
    
    for (int i=0; i<n; i++){
        al[i+1]=a[n*3-i-1];
        L[0]+=al[i+1];
    }
    qsort (al,n+1,sizeof(long long),dessort);
    for (int i=0; i<n; i++){
        tmp=a[2*n-i-1];
        if (tmp<al[1]){
            L[i+1]=L[i]-al[1]+tmp;
            al[1]=tmp;
            long long bf=1;
            while(1){
                if (bf*2>n){
                    break;
                }
                if (al[bf*2]>=al[bf*2+1] || bf*2+1>n){
                    if (al[bf]<al[bf*2]){
                        tmp=al[bf];
                        al[bf]=al[bf*2];
                        al[bf*2]=tmp;
                        bf=bf*2;
                    } else {
                        break;
                    }
                } else {
                    if (al[bf]<al[bf*2+1]){
                        tmp=al[bf];
                        al[bf]=al[bf*2+1];
                        al[bf*2+1]=tmp;
                        bf=bf*2+1;
                    } else {
                        break;
                    }
                }
            }
        } else {
            L[i+1]=L[i];
        }
    }
    tmp=R[0]-L[n];
    for (int i=0; i<=n; i++){
        tmp=tmp>(R[i]-L[n-i])?tmp:(R[i]-L[n-i]);
    }
    printf("%lld\n",tmp);
    return 0;
}


Measured memory_bytes: 6392
#include <iostream>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
#define rep0(i, n) for(int i=0; i<(int)(n);i++)
typedef int64_t lint;
using namespace std;

int main(){
    lint n, k;
    cin >> n >> k;
    vector<lint> a(n);
    rep0(i, n){
        cin >> a[i];
    }
    lint kk = k * (k - 1) / 2;
    boost::multiprecision::cpp_int ans = 0;
    for (int i = 0; i < n; ++i) {
        lint left = 0;
        lint right = 0;
        for (int j = 0; j < n; ++j) {
            if(a[i] > a[j]){
                if(i > j)left ++ ;
                if(i < j)right ++ ;
            }
        }
        rep0(j,left)
        {
            ans += kk;
            ans %= 1000000007;
        }
        rep0(j,right)
        {
            ans += kk;
            //ans %= 1000000007;
            ans += k;
            ans %= 1000000007;
        }     

    }
    cout << ans << endl;
}

Measured memory_bytes: 384
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)

from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations, combinations_with_replacement
from itertools import accumulate
from math import ceil, sqrt, pi

MOD = 10 ** 9 + 7
INF = 10 ** 18

N, M = map(int, input().split())
H = list(map(int, input().split()))
AB = [list(map(int, input().split())) for _ in range(M)]

graph = [[] for _ in range(N + 1)]

for a, b in AB:
    graph[a].append(b)
    graph[b].append(a)
#print(graph)

ans = 0
for i in range(1, N + 1):
    tmp = H[i - 1]
    flag = 1
    for g in graph[i]:
        if tmp <= H[g - 1]:
            flag = 0
    if flag:
        #print(i)
        ans += 1
print(ans)

Measured memory_bytes: 102460
a,b,c,d,e,f=map(int,input().split())
a=100*a
b=100*b
dp1=[0]*(f+1)
dp2=[0]*(f+1)
for i in range(f+1):
    if i%a==0:
        if i+a<=f:
            dp1[i+a]=1
for i in range(f+1):
    if i==0 or dp1[i]==1:
        if i+b<=f:
            dp1[i+b]=1
for i in range(f+1):
    if i%c==0:
        if i+c<=f:
            dp2[i+c]=1
for i in range(f+1):
    if i==0 or dp2[i]==1:
        if i+d<=f:
            dp2[i+d]=1
#print(dp1)
#print(dp2)
ans=[-1,-1,-1]
for i in range(f+1):
    if dp1[i]==1:
        x=min(f-i,(i//100)*e)
        k=-1
        for j in range(x,-1,-1):
            if dp2[j]==1 or j==0:
                k=j
                if ans[0]<100*k/(i+k):
                    ans=[100*k/(i+k),i+k,k]
                break
print(str(ans[1])+" "+str(ans[2]))


Measured memory_bytes: 3188
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class Main {
 private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1);
 private ArrayList<Integer> cases = new ArrayList<Integer>();

 private String inputData = null;

 public static void main(String[] args) {
  new Main().start();
 }

 public void start() {
  while (true) {
   try {
    this.inputData = reader.readLine();
   } catch (IOException e) {
    e.printStackTrace();
   }
   if (this.inputData.equals("0")) {
    break;
   }
   
   this.cases.add(Integer.parseInt(
   this.inputData));

  }

   for (int i = 0; i < this.cases.size(); i++) {
    System.out.println("Case " + (i+1) + ": " + this.cases.get(i));
   }

 }

}

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

using namespace std;

long long n,k,a,b,c,q[200005],nr,rs;
string s,x;

int main() 
{
    cin>>a>>b>>c;
    cout<<1LL*(int(ceil(a*1.0/b*1.0))*c)<<endl;
}

Measured memory_bytes: 3628
import std.stdio;
import std.math;
import std.conv;
import std.string;
import std.algorithm;
import std.array;

void main() {
  while(true) {
    string line = readln.chomp;
    if (stdin.eof) break;
    uint[] data = line.split(" ").map!(to!(uint)).array;
    uint a = data[0];
    uint b = data[1];
    uint n = data[2];
    uint sum = 0;
    a %= b;
    for(uint i = 0; i < n; i++) {
      a *= 10;
      sum += a / b;
      a %= b;
      if (a == 0) break;
    }
    writeln(sum);
  }
}

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

int n;

char s[110];

int main() {
    cin >> (s + 1);
    int len = strlen(s + 1);
    for (int i = 1; i <= len; ++i) {
        if (((i & 1) && s[i] == 'L') || (!(i & 1) && s[i] == 'R')) {
            puts("No");
            return 0;
        }
    }
    puts("Yes");
}

Measured memory_bytes: 256
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include <sstream>
#include <algorithm>
#include <deque>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <climits>
#include <bitset>
#include <functional>
#include <numeric>
#include <ctime>
#include <cassert>
#include <cstring>
#include <fstream>

using namespace std;

int main() {
    int n;
    cin >> n;
    long long a = 2, b = 1;

    for (int i = 2; i <= n; i++) {
        long long c = a + b;
        a = b;
        b = c;
    }
    cout << b << endl;
    return 0;
}

Measured memory_bytes: 256
s = input()
t = input()
s1 = sorted(s)
t1 = sorted(t,reverse=True)

flag = -10
for i in range(min(len(s) , len(t))):
    if s1[i] < t1[i]:
        flag = 1
        break
    elif s1[i] == t1[i]:
        continue
    elif s1[i] > t1[i]:
        flag = 2
        break

if (flag == -10) and (len(s) < len(t)):
    print('Yes')
    
if (flag == -10) and (len(s) >= len(t)):
    print('No')
    
if flag == 1:
    print('Yes')
if flag == 2:
    print('No')

Measured memory_bytes: 9036
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include <list>
#include <math.h>
#include <iomanip>
#define rep(i,n) for(int i=1;i<=(n);i++)
using namespace std;


int A,B,K;
int l[110];
int c=0;

int main(){
  cin>>A>>B>>K;
  rep(i, min(A,B)){
    if(A%i == 0 && B%i == 0){
      c++;
      l[c] = i;
    }
  }
  for(int i=c;i>0;i--){
    if( (c+1-i) == K) cout << l[i] << endl;
  }

}

Measured memory_bytes: 256
import Data.List
main=do
    [a1,a2,a3]<-map read.words<$>getLine::IO[Int]
    print $ minimum[abs(a1-a2)+abs(a2-a3),abs(a1-a3)+abs(a3-a2),abs(a2-a1)+abs(a1-a3),abs(a2-a3)+abs(a3-a1),abs(a3-a1)+abs(a1-a2),abs(a3-a2)+abs(a2-a1)]


Measured memory_bytes: 508
#define _GLIBCXX_DEBUG
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ll long long
#define all(x) (x).begin(),(x).end()
template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b;return true;}return false;}
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
const int INF = 1000000000;
typedef pair<int,int> P;

int main() {
    int H, W;
    cin >> H >> W;
    vector<string>cells(H);
    vector<P>bombs;
    vector<vector<int>>ans(H, vector<int>(W));


    for (int i=0; i<H; i++){
        cin >> cells[i];
    }
    for (int i=0; i<H; i++){
        for (int j=0; j<W; j++){
            if (cells[i][j] == '#')bombs.push_back(P(i,j));
        }
    }

    for (int i=0; i<bombs.size(); i++){
        int y, x;
        y = bombs[i].first;
        x = bombs[i].second;
        //左上
        if (x-1 >= 0 and y-1 >= 0)ans[y-1][x-1]++;
        //上
        if (y-1 >= 0)ans[y-1][x]++;
        //右上
        if (y-1 >= 0 and x+1 < W)ans[y-1][x+1]++;
        //右
        if (x+1 < W)ans[y][x+1]++;
        //右下
        if (x+1 < W and y+1 < H)ans[y+1][x+1]++;
        //下
        if (y+1<H)ans[y+1][x]++;
        //左下
        if (x-1 >= 0 and y+1 < H)ans[y+1][x-1]++;
        //左
        if (x-1 >= 0)ans[y][x-1]++;
    }

    for (int i=0; i<H; i++){
        for (int j=0; j<W; j++){
            if (cells[i][j] == '#')cout << "#";
            else cout << ans[i][j];
        }
        cout << endl;
    }
}

Measured memory_bytes: 256
#include <stdio.h>
#include <cmath>
#include <algorithm>

#define NUM 1000500

int main(){
	int* table = new int[NUM];
	int limit;

	for(int i=0; i < NUM;i++)table[i] = 1;
	table[0] = 0;
	table[1] = 0;

	limit = sqrt(NUM);

	for(int i=2;i<=limit;i++){
		if(table[i] == 1){
			for(int k=2*i;k < NUM; k += i){
				table[k] = 0;
			}
		}
	}

	int a,b,index,array[1000],sum,a_key,b_key;

	while(true){
		scanf("%d %d",&a,&b);
		if(a == 0 && b == 0)break;

		limit = a/2 + 100;
		index = 0;

		if(a%2 == 0)array[index++] = 2;
		while(a%2 == 0)a /= 2;

		for(int i = 3; i <= limit; i += 2){
			if(table[i] == 1 && a%i == 0){
				array[index++] = i;
				while(a%i == 0){
					a /= i;
				}
			}
		}

		sum = 0;

		if(index == 0 && table[a] == 1){
			a_key = a;
		}else{

			for(int i = 0; i <= index-2; i++){
				sum += array[i];
			}

			a_key = array[index-1] - sum;
		}


		limit = b/2 + 100;
		index = 0;

		if(b%2 == 0)array[index++] = 2;
		while(b%2 == 0)b /= 2;

		for(int i = 3; i <= limit; i += 2){
			if(table[i] == 1 && b%i == 0){
				array[index++] = i;
				while(b%i == 0){
					b /= i;
				}
			}
		}

		sum = 0;

		if(index == 0 && table[b] == 1){
			b_key = b;
		}else{

			for(int i = 0; i <= index-2; i++){
				sum += array[i];
			}

			b_key = array[index-1] - sum;
		}

		if(a_key > b_key)printf("a\n");
		else{
			printf("b\n");
		}

	}
	return 0;
}

Measured memory_bytes: 6496
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
//deque/functional/iterator/list/map/memory/numeric/queue/set/stack/utility/vector
//#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int mod=1e9+7;

int main(){
    ios::sync_with_stdio(false);
    ll a,b,c;
    ll n,m;
    cin>>n>>m;
    ll sum=0;
    if(m>=2*n){
        sum+=n;
        m=m-2*n;
        sum+=m/4;
    }else{
        sum+=m/2;
    }
    cout<<sum<<endl;

    return 0;
}


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

int main(){
  int n;
  cin >> n;
  int h[n];
  rep(i,n)cin >> h[i];
  int max=1;
  rep(i,n) {
    if(h[i]>max)max=h[i];
    if(max-h[i]>=2){
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;
  return 0;
}


Measured memory_bytes: 640
import java.io.*;
import java.lang.*;

public class Main {
	public static void main (String[] args) throws IOException
	{
	   BufferedReader br = new BufferedReader( new InputStreamReader ( System.in));
	   String line1= br.readLine();
	   String strs1[]= line1.trim().split("\\s+");
	   int n= Integer.parseInt( strs1[0] );
	   int k= Integer.parseInt(strs1[1]);
	   
	   int arr[]= new int[n];
	   
	   String line=br.readLine();
	   String strs[]=line.trim().split("\\s+");
	   
	   for(int i=0; i<n ;i++)
	   arr[i]=Integer.parseInt(strs[i]);
	   
	   int calc[]=new int[n];
	   calc[0]=0;
	   
	   for(int i=1;i<n ; i++)
	   {
	       int m= calc[i-1] + Math.abs(arr[i]-arr[i-1] );
	       int count=1;
	       for(int j=i-2 ; j>=0 && count<k ; j--)
	       {
	           int comp=calc[j] + Math.abs(arr[j]-arr[i]);
	           count+=1;
	           m=Math.min(m , comp);
	       }
	       
	       calc[i]=m;

	   }
	   System.out.println( calc[n-1]);
		//code
	}
}

Measured memory_bytes: 36060
n= int(input())
x= [0]*n
y= [0]*n
for i in range(n):
    x[i],y[i]=map(int,input().split())


import itertools
import  math
lis = list(itertools.permutations(range(n),n))

al=0
for elem in lis:
    [al := al + math.sqrt( (x[elem[i]]-x[elem[i+1]])**2 +  (y[elem[i]]-y[elem[i+1]])**2) for i in range(n-1)]

print(al/len(lis))

Measured memory_bytes: 13720
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int INF = 1e9;
const ll LINF = 1e18;
inline ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; }
inline ll lcm(ll a, ll b) { return a / gcd(a, b)*b; }
template<class S,class T> ostream& operator << (ostream& out,const pair<S,T>& o){ out << "(" << o.first << "," << o.second << ")"; return out; }
template<class T> ostream& operator << (ostream& out,const vector<T>& V){ for(int i = 0; i < V.size(); i++){ out << V[i]; if(i!=V.size()-1) out << " ";} return out; }
template<class T> ostream& operator << (ostream& out,const vector<vector<T> >& Mat){ for(int i = 0; i < Mat.size(); i++) { if(i != 0) out << endl; out << Mat[i];} return out; }
template<class S,class T> ostream& operator << (ostream& out,const map<S,T>& mp){ out << "{ "; for(auto it = mp.begin(); it != mp.end(); it++){ out << it->first << ":" << it->second; if(mp.size()-1 != distance(mp.begin(),it)) out << ", "; } out << " }"; return out; }
template<typename T>vector<T> make_v(size_t a){return vector<T>(a);}
template<typename T,typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v<T>(ts...))>(a,make_v<T>(ts...));}
template<typename T,typename V> typename enable_if<is_class<T>::value==0>::type fill_v(T &t,const V &v){t=v;}
template<typename T,typename V> typename enable_if<is_class<T>::value!=0>::type fill_v(T &t,const V &v){for(auto &e:t) fill_v(e,v);}
/*
 <url:https://atcoder.jp/contests/abc146/tasks/abc146_d>
 問題文============================================================
 D - Coloring Edges on Tree
 =================================================================
 解説=============================================================
 
 ================================================================
 */

template<class Type>
Type solve(Type res = Type()){
    int N; cin >> N;
    vector<vector<int>> G(N);
    vector<pii> edges;
    for(int i = 0; i < N-1;i++){
        int a,b; cin >> a >> b;
        a--; b--;

        G[a].push_back(b);
        G[b].push_back(a);
        edges.push_back(pii(a,b));
        
    }
    
    int M = -1;
    map<pii,int> mp;
    function<void(int,int)> rec = [&](int n,int pre){
        set<int> st;
        for(int next:G[n]){
            if(next == pre) continue;
            if(mp[pii(min(n,next),max(n,next))]) st.insert(mp[pii(min(n,next),max(n,next))]);
        }
        
        int ng = mp[pii(min(n,pre),max(n,pre))];
        int num = 1;
        for(int next:G[n]){
            if(next == pre) continue;
            if(ng == num) num++;
            
            M = max(M,num);
            mp[pii(min(n,next),max(n,next))] = num;
            num++;
            rec(next,n);
        }
        return;
    };
    rec(0,-1);
    
    cout << M << endl;
    for(auto e:edges){
        cout << mp[pii(e.first,e.second)] << endl;
    }
    
    return res;
}
int main(void) {
    cin.tie(0); ios_base::sync_with_stdio(false);
    solve(0);
    // cout << fixed << setprecision(15) << solve<ll>() << endl;
    return 0;
}


Measured memory_bytes: 21372
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <vector>
#include <utility>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <stack>
#include <ctime>
#include <fstream>
#include <stdarg.h>
using namespace std;
const bool debug=false;
const bool INJUDGE=false;
#define FASTERCIN cin.tie(0);ios_base::sync_with_stdio(false)
typedef long long ll;
/*Time:2018.3.17
Status:
Type:Atcoder Round
Author:XIZCM*/
int n;
map<string,int> m;
string s;
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>s;
		m[s]++;
	}
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>s;
		m[s]--;
	}
	int maxn=0;
	for(map<string,int>::iterator it=m.begin();it!=m.end();it++){
		maxn=max(it->second,maxn);
	}
	cout<<maxn<<endl;
	return 0;
}


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

namespace Algorithm
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = new HashSet<int>() { 1, 3, 5, 7, 8, 10, 12 };
            var b = new HashSet<int>() { 4, 6, 9, 11};
            var c = new HashSet<int>() { 2};

            var xy = Console.ReadLine().Split().Select(int.Parse).ToArray();
            int x = xy[0], y = xy[1];

            if (a.Contains(x) && a.Contains(y)
                || b.Contains(x) && b.Contains(y)
                || c.Contains(x) && c.Contains(y))
                Console.WriteLine("Yes");
            else
                Console.WriteLine("No");
            
        }
    }
}


Measured memory_bytes: 13524
N, M = map(int, input().split())
A, B, C = [], [], []
for _ in range(N):
  a, b, c = map(int, input().split())
  A.append(a)
  B.append(b)
  C.append(c)
D, E, F = [], [], []
for _ in range(M):
  d, e, f = map(int, input().split())
  D.append(d)
  E.append(e)
  F.append(f)

orig_X = sorted(set([0] + D))
orig_Y = sorted(set([0] + C))
                
X = {x: i for i, x in enumerate(orig_X)}
Y = {y: i for i, y in enumerate(orig_Y)}
max_X = len(X) - 1
max_Y = len(Y) - 1
#print(X, Y)

movable = [(-1, 0), (1, 0), (0, -1), (0, 1)]
blocked = {}
# (x, y) -> stands at (x+0.5, y+0.5)
for a, b, c in zip(A, B, C):
  y = Y[c]
  Xa = -1
  Xb = -1
  for i, x in enumerate(orig_X):
    if Xa < 0 and x >= a:
      Xa = i
    if x > b:
      break
    Xb = i
  #for x in range(X[a], X[b]):
  for x in range(Xa, Xb):
    if y < max_Y:
      if (x, y) not in blocked:
        blocked[(x, y)] = set()
      blocked[(x, y)].add((0, -1))
    if y > 0:
      if (x, y-1) not in blocked:
        blocked[(x, y-1)] = set()
      blocked[(x, y-1)].add((0, +1))

for d, e, f in zip(D, E, F):
  x = X[d]
  Ye = -1
  Yf = -1
  for i, y in enumerate(orig_Y):
    if Ye < 0 and y >= e:
      Ye = i
    if y > f:
      break
    Yf = i
  # for y in range(Y[e], Y[f]):
  for y in range(Ye, Yf):
    if (x, y) not in blocked:
      blocked[(x, y)] = set()
    blocked[(x, y)].add((-1, 0))
    if x > 0:
      if (x-1, y) not in blocked:
        blocked[(x-1, y)] = set()
      blocked[(x-1, y)].add((+1, 0))

#print(sorted(blocked))

visited = [0] * max_X * max_Y
def get_visited(x, y):
  return visited[x * max_Y + y]
def set_visited(x, y):
  #print(x,y)
  visited[x * max_Y + y] = True

to_visit = [(X[0], Y[0])]
while to_visit:
  #print(to_visit)
  x, y = to_visit.pop()
  if x < 0 or x >= max_X or y < 0 or y >= max_Y:
    print('INF')
    exit()
  if get_visited(x, y):
    continue
  set_visited(x, y)
  for d in movable:
    if (x, y) in blocked and d in blocked[(x, y)]:
      continue
    to_visit.append((x + d[0], y + d[1]))

ans = 0
for x in range(0, max_X):
  for y in range(0, max_Y):
    if get_visited(x, y):
      ans += (orig_X[x+1] - orig_X[x]) * (
        orig_Y[y+1] - orig_Y[y])
print(ans)

Measured memory_bytes: 544456
import sys
s=input()
k=int(input())
lengthofs=len(s)

if lengthofs == 1:
	print(k//2)
	sys.exit()

i=0
j=0
while i+1 < lengthofs :
	if s[i] != s[i+1]:
		j=1
	i=i+1
if j == 0:
	print((lengthofs*k)//2)
	sys.exit()

i=0
j=1
ans=0
while i+1 < lengthofs :
	if s[i] == s[i+1]:
		j=j+1
	else:
		ans=ans+(j//2)
		j=1
	i=i+1
ans=ans+(j//2)
ans=ans*k

if s[0]!=s[lengthofs-1]:
	print(ans)
else:
	i=0
	while s[i]==s[i+1]:
		i=i+1
	i=(i+1)%2
	j=1
	while s[lengthofs-j] == s[lengthofs-j-1]:
		j=j+1
	j=j%2
	if i*j==1:
		ans=ans+k-1
	print(ans)

Measured memory_bytes: 3064
// inputに入力データ全体が入る
    // fizzBuzz
    function Main(inputString) {
        // 1行目がinput[0], 2行目がinput[1], …に入る
        let inputNumber = parseInt(inputString);
        let arrNotFizzBuzzNumber = [];
        for(let i = 0; i <= inputNumber; i++ ){
            if( !((i % 3 == 0) || (i % 5 == 0))){
                arrNotFizzBuzzNumber.push(i);
            }
        }

            let sum = 0;
            arrNotFizzBuzzNumber.forEach(function(tmpNumber){
                sum += tmpNumber;
            });

    	//出力
    	console.log(sum);
    }
    //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
    //Main('115')

Measured memory_bytes: 51372
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int n,m,sum;
int a[10005]; 
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>a[i];
		sum+=a[i];
	}
	if(sum>n)
		cout<<-1;
	else
		cout<<n-sum;
return 0;
}


Measured memory_bytes: 3664
#include <bits/stdc++.h>
using namespace std;
template<typename T = int> vector<T> create(size_t n){ return vector<T>(n); }
template<typename T, typename... Args> auto create(size_t n, Args... args){ return vector<decltype(create<T>(args...))>(n, create<T>(args...)); }
template<typename T>
struct segtree {
    vector<T> t;
    int n;
    segtree(int n): n(n) {
        t.assign(2 * n, T());
    }
    void update(int p, T v){
        for(t[p += n] = v; p >>= 1; )
            t[p] = t[p<<1] + t[p<<1|1];
    }
    void add(int p, T v){
        p += n;
        t[p] = t[p] + v;
        while(p >>= 1) t[p] = t[p<<1] + t[p<<1|1];
    }
    T query(int l, int r){
        T cl = T(), cr = T();
        for(l += n, r += n; l < r; l >>= 1, r >>= 1){
            if(l&1) cl = cl + t[l++];
            if(r&1) cr = t[--r] + cr;
        }
        return cl + cr;
    }
};
struct or_t {
	int v;
	or_t(): v(0){}
	or_t(int v): v(v){}
};
or_t operator + (or_t a, or_t b){
	return or_t(a.v | b.v);
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int n; cin >> n;
	string s; cin >> s;
	segtree<or_t> seg(n);
	for(int i = 0; i < n; i++){
		seg.update(i, 1<<(s[i] - 'a'));
	}
	int q; cin >> q;
	while(q--){
		int ty, x, y; cin >> ty >> x;
		if(ty == 1){
			char c; cin >> c;
			seg.update(x - 1, 1<<(c - 'a'));
		} else {
			cin >> y;
			cout << __builtin_popcount(seg.query(x - 1, y).v) << '\n';
		}
	}
	return 0;
}

Measured memory_bytes: 4892
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize(3)
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma comment(linker, "/stack:200000000")
#include <bits/stdc++.h>
#define SIZE 300010
#define rep(i, a, b) for (int i = a; i <= b; ++i)
#define ll long long
#define mp make_pair
#define pi acos(-1.0)
#define eps 1e-6
using namespace std;
void io() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); }
ll n, ans, k, tmp;
string s;
ll sol(string s) {
	ll ans = 0, tmp = 0;
	ll len = s.length();
	ll fir = s[0] - '0';
	for (ll i = len - 1; i >= 2; --i) {
		for (ll j = i - 1; j; --j) {
			ans += 9ll * 9ll;
		}
	}
	int pos = 1;
	bool f = true;
	rep(i, 1, (s.length() - 1)) if (s[i] != '0') { pos = i; f = false; break; }
	tmp += s[pos] - '0';
	if (!f) for (int i = pos + 1; i < s.length(); ++i) tmp += 9ll;
	/*if (!f) */for (int i = 1; i < s.length(); ++i) tmp += 9ll * (fir - 1);
	return ans + tmp;
}
int main() {
	io(); cin >> s >> k;
	ll len = s.length();
	ll fir = s[0] - '0';
	if (k == 1) cout << 9 * (len - 1) + fir;
	else if (k > len) cout << 0;
	else if (k == 2) cout << sol(s);
	else if (k == 3) {
		for (ll i = len - 1; i >= 3; --i) {
			for (ll j = i - 1; j >= 2; --j) {
				for (ll k = j - 1; k; --k) {
					ans += 9ll * 9ll * 9ll;
				}
			}
		}
		for (int i = 1; i < s.length() - 1; ++i) {
			for (int j = i + 1; j < s.length(); ++j) {
				ans += 9ll * 9ll * (fir - 1ll);
				//tmp += (s[i] - '0') * (s[j] - '0');
			}
		}
		int pos = 1, ps = 2; bool ff = false;
		rep(i, 1, (s.length() - 1)) if (s[i] != '0') { ff = true; pos = i; break; }
		rep(i, (pos + 1), (s.length() - 1)) if (s[i] != '0') { ps = i; break; }
		/*for (int i = pos + 1; i < s.length() - 1; ++i) {
			for (int j = ps + 1; j < s.length(); ++j) {
				tmp += 9ll * 9ll;
			}
		}*/
		string ss;
		rep(i, pos, (s.length() - 1)) ss.push_back(s[i]);
		if (ff) tmp += sol(ss);
		cout << ans + tmp;
	}
}

Measured memory_bytes: 256
fun main(args: Array<String>) {
    val (H,W) = readLine()!!.split(" ").map {it.toInt()}

    repeat(W+2) { 
        print("#")
     }
    print("\n")
   repeat(H){ 
        println("#${readLine().toString()}#")
    }
    repeat(W+2) { 
        print("#")
     }
}

Measured memory_bytes: 37864
#include<bits/stdc++.h>
using namespace std;
int a[210],b[210],la,lb,i=100;
int main()
{
	long long n;
	scanf("%lld",&n);
	n++;
	while(n>1)
	{
		if(n&1)n--,a[++la]=i--;
		else n>>=1,b[++lb]=i--;
	}
	printf("%d\n",(la+lb)*2);
	for(int j=1;j<=la;j++)
		printf("%d ",a[j]);
	for(int j=lb;j>=1;j--)
		printf("%d ",b[j]);
	for(int j=100-la-lb+1;j<100;j++)
		printf("%d ",j);
	printf("%d\n",100);
	return 0;
}

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

int main() {
  int n;
  string s,t;
  cin>>s>>t;
  sort(ALL(s));
  sort(ALL(t));
  reverse(ALL(t));
  Yes(s<t);


  return 0;
}


Measured memory_bytes: 256
#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

int main(void)
{
    int n, k;
    unsigned long long na = 0;
    scanf("%d %d", &n, &k);

    if (k >= n)
    {
        printf("0\n");
    }
    else
    {
        vector<int> hv;
        while (n--)
        {
            int h;
            scanf("%d", &h);
            hv.push_back(h);
        }

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

        n = hv.size() - k;

        for (int i=0; i<n; ++i)
        {
            na += hv[i];
        }
        printf("%llu\n", na);
    }

    return 0;
}

Measured memory_bytes: 1400
macro_rules! scan( ($text:expr, $($arg:ident),*) => { scan!(std::io::stdin().bytes().map(|c| c.unwrap()) => $text, $($arg),*) }; ($input:expr => $text:expr, $($arg:ident),*) => {{ use std::io::Read; use std::str::FromStr; /* typesafe macros :) */ let text: &'static str = $text; let stdin: &mut Iterator<Item = u8> = &mut ($input); let mut text = text.bytes(); $( loop { match text.next() { Some(b'{') => match text.next() { Some(b'{') => assert_eq!(Some(b'{'), stdin.next()), Some(b'}') => { let s: Vec<u8> = match text.next() { Some(c) => stdin.take_while(|&ch| ch != c).collect(), None => stdin.take_while(|ch| !b"\t\r\n ".contains(ch)).collect(), }; let s = match std::str::from_utf8(&s) { Ok(s) => s, Err(e) => { let n = e.valid_up_to(); if n == 0 { panic!("input was not valid utf8: {:?}", s); } else { panic!("input was only partially valid utf8: \"{}\" followed by {:?}", std::str::from_utf8(&s[..n]).unwrap(), &s[n..]); } } }; $arg = FromStr::from_str(s).expect(&format!("could not parse {} as target type of {}", s, stringify!($arg))); break; } Some(_) => panic!("found bad curly brace"), None => panic!("found single open curly brace at the end of the format string"), }, Some(c) => assert_eq!(Some(c), stdin.next()), None => panic!("Bad read! format string: did not contain {{}}"), } })* for c in text { assert_eq!(Some(c), stdin.next()); } }}; );

fn main() {
    let (d, n): (u32, u32);
    scan!("{} {}\n", d, n);

    let mut nn = n;
    if n == 100 {
        nn = nn + 1;
    }
    let x: u32 = 100;
    let ans = nn * x.pow(d);
    println!("{}", ans);
}


Measured memory_bytes: 4352
#include <stdio.h>
#include <assert.h>
#include <fstream>
#include <iostream>
#include <algorithm>
#include <array>
#include <vector>
#include <queue>
#include <set>
#include <cmath>
//#include <unordered_map>
//#include <unordered_set>
//#include <boost/container/static_vector.hpp>
//#include <boost/unordered_set.hpp>
//#include <boost/unordered_map.hpp>
//#include <unistd.h>

std::string s;

int main(int argc, char **argv) {
    std::cin >> s;

    std::string t;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != 'x') {
            //std::cout << i << std::endl;
            t.push_back(s[i]);
        }
    }
    //std::cout << t << std::endl;

    for (int i = 0; i < t.size(); i++) {
        if (t[i] != t[t.size()-1-i]) {
            std::cout << -1 << std::endl;
            return 0;
        }
    }

    std::string front, back;
    int cnt = 0;
    for (int i = 0; i < s.size(); i++) {
        if (t.size() % 2 == 1) {
            if (cnt == t.size() / 2 && s[i] != 'x') {
                // nothing to do
            } else if (cnt <= t.size() / 2) {
                front.push_back(s[i]);
            } else {
                back.push_back(s[i]);
            }
        } else {
            if (cnt == t.size() / 2 && s[i] == 'x') {
                // nothing to do
            } else if (cnt < t.size() / 2) {
                front.push_back(s[i]);
            } else {
                back.push_back(s[i]);
            }
        }
        if (s[i] != 'x') {
            cnt++;
        }
    }

    std::reverse(back.begin(), back.end());
    //std::cout << front.size() << " " << back.size() << std::endl;

    int ret = 0;
    while (0 < front.size() || 0 < back.size()) {
        if (front.size() == 0) {
            assert(back.back() == 'x');
            front.push_back('x');
            ret++;
        } else if (back.size() == 0) {
            assert(front.back() == 'x');
            back.push_back('x');
            ret++;
        } else if (front.back() == back.back()) {
            front.pop_back();
            back.pop_back();
        } else {
            assert(front.back() == 'x' || back.back() == 'x');
            if (front.back() == 'x') {
                back.push_back('x');
            } else {
                front.push_back('x');
            }
            ret++;
        }
    }
    std::cout << ret << std::endl;
    return 0;
}



Measured memory_bytes: 640
#include <bits/stdc++.h>
using namespace std;
#define int long long
typedef pair<int,int> ii;
#define F first
#define S second
#define sqr(x) (x)*(x)
#define pb(x) push_back(x)
#define sz(x) (int)x.size()
#define mp(x,y) make_pair(x,y)
#define all(x) (x).begin(),(x).end()
#define rep(i,x,y) for(int i=x;i<(y);++i)
#define IOS ios_base::sync_with_stdio(0);cin.tie(0)
/* start */

signed main(){
   IOS;
   int a,b,c,k; cin >> a >> b >> c >> k;
   int ans = 0;
   if(k>=a){
      ans+=a;
      k-=a;
   }
   else{
      ans+=k;
      k=0;
   }
   if(k>=b){
      k-=b;
   }
   else{
      k=0;
   }
   if(k>=c){
      ans-=c;
      k-=c;
   }
   else{
      ans-=k;
      k=0;
   }
   cout << ans << '\n';
}

Measured memory_bytes: 3652
#include <iostream>
#define ll long long
using namespace std;
ll N,M;
ll A[100005];
ll a[100005];
ll b[100005];
ll dist(ll x,ll y)
{
    if(x<=y)return y-x;
    return M-x+y;
}
ll cost(ll x)
{
    ll rez=0;
    for(ll i=2;i<=N;i++)
        rez+=min(1+dist(x,A[i]),dist(A[i-1],A[i]));
    return rez;
}
void addprog(ll st,ll dr,ll p,ll q)
{
    b[st]+=p;b[dr+1]-=p;
    a[st]+=q;a[dr+1]-=q;
    b[st]-=st*q;b[dr+1]+=st*q;
}
int main()
{
    cin>>N>>M;
    ll mini=1LL<<60;
    for(ll i=1;i<=N;i++)
        {cin>>A[i];}
    for(ll i=2;i<=N;i++)
    {
        if(A[i-1]<A[i])
        {
            addprog(1,A[i-1],dist(A[i-1],A[i]),0);
            addprog(A[i]+1,M,dist(A[i-1],A[i]),0);
            addprog(A[i-1]+1,A[i],dist(A[i-1],A[i]),-1);
        }
        else
        {
            addprog(A[i]+1,A[i-1],dist(A[i-1],A[i]),0);
            addprog(A[i-1]+1,M,dist(A[i-1],A[i]),-1);
            addprog(1,A[i],A[i],-1);
        }
    }
    for(int i=1;i<=M;i++)
    {
        a[i]+=a[i-1];
        b[i]+=b[i-1];
    }
    for(int i=1;i<=M;i++)
        mini=min(mini,i*a[i]+b[i]);
    cout<<mini;
    return 0;
}


Measured memory_bytes: 2560
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

from bisect import bisect_right
N = int(input())
ab = [list(mapint()) for _ in range(N)]
cd = [list(mapint()) for _ in range(N)]
ab.sort(reverse=True)
cd.sort(key=lambda x: x[1])
checked = [0]*N

ans = 0
for n in range(N):
    a, b = ab[n]
    for i in range(N):
        if checked[i]:
            continue
        c, d = cd[i]
        if a<c and b<d:
            ans += 1
            checked[i] = 1
            break

print(ans)

Measured memory_bytes: 9212
// include
// ------------------------------------------------
#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;

// func
// ------------------------------------------------
int CalcSumOfDigit(int n);      // 各桁の和を計算する。
long long getDigit(long long n);      // 数字の桁数を取得する。
string upper(string str);       // 英字を大文字に変換する。
string lower(string str);       // 英字を小文字に変換する。

// define
// ------------------------------------------------
#define all(a)        (a).begin(),(a).end()
#define rall(a)       (a).rbegin(),(a).rend()
#define sz(a)         int((a).size())
#define rep(i,n)      for(int(i)=0;(i)<(n);(i)++)
#define repe(i,n)     for(int(i)=0;(i)<=(n);(i)++)
#define vsort(v)      sort((v).begin(),(v).end())
#define rvsort(v)     sort(rall((v)))
#define vi            vector<int>
#define GCD(a,b)      __gcd((a),(b))
#define LCM(a,b)      ((a)/GCD((a),(b))*(b))
#define kiriage(a,b)  ((a)+(b)-1)/(b)

const int INF = 1e9;

typedef long long ll;
typedef unsigned long long ull;
typedef vector<ll> vll;

// code
// ------------------------------------------------
int main()
{

  ll n;cin >> n;
  vll a(n),b(n);

  rep(i,n)
  {
    cin >> a[i];
    b[i] = a[i];
  }

  vsort(b);

  ll m1 = b[n-1];
  ll m2 = b[n-2];

  rep(i,n)
  {
    if(a[i] == m1)
      cout << m2 << endl;
    else
    {
      cout << m1 << endl;
    }
    
  }

  return 0;
}
// funcの実体
// ------------------------------------------------
ll getDigit(ll n)
{
  int i = 1;
  while(1)
  {
    n = n / 10;
    if(n == 0)
      break;
    i++;
  }
  return i;
}
ll CalcSumOfDigit(ll n)
{
  ll s = 0;
  while(n)
  {
    s += n % 10;
    n = n / 10;
  }
  return s;
}

string upper(string str)
{
  for(auto itr = str.begin();itr != str.end() ; itr++)
  {
    if(97 <= *itr && *itr <= 122)
    {
      *itr = *itr - 32;
    }
  }
  return str;
}

string lower(string str)
{
  for(auto itr = str.begin();itr != str.end() ; itr++)
  {
    if(65 <= *itr && *itr <= 90)
    {
      *itr = *itr + 32;
    }
  }
  return str;
}


Measured memory_bytes: 4736
### constant

MAX_INT = 1 << 30

### main

loop do
  n = gets.to_i
  break if n == 0

  mkts = {}
  for i in (1..n)
    strs = gets.strip.split
    k = strs.shift.to_i

    k.times do
      name = strs.shift
      val = strs.shift.to_i

      mkts[name] = [] if mkts[name].nil?
      mkts[name] << [i, val]
    end
  end
  #p mkts

  goods = []
  ng = false

  q = gets.to_i
  q.times do
    name = gets.strip
    goods << name

    ng = true if mkts[name].nil?
  end
  #p goods

  edges = (n + 1).times.map{[]}
  nbrs = (n + 1).times.map{[]}

  m = gets.to_i
  m.times do
    s, t, d = gets.split.map(&:to_i)
    edges[s][t] = edges[t][s] = d
    nbrs[s] << t
    nbrs[t] << s
  end
  #p edges
  #p nbrs

  if ng
    puts 'impossible'
    next
  end

  pbits = (n + 1).times.map{0}
  allbits = (1 << q) - 1
  sumval = 0

  for i in (0...q)
    name = goods[i]
    min_val = mkts[name].map{|m| m[1]}.min
    sumval += min_val
    for mkt in mkts[name]
      k, val = mkt
      if val == min_val
        pbits[k] |= (1 << i)
      end
    end
  end
  #p pbits
  #p allbits

  dists = (n + 1).times.map{(allbits + 1).times.map{MAX_INT}}
  dists[0][0] = 0

  q = [[0, 0]]

  while ! q.empty?
    u = q.min{|a, b| dists[a[0]][a[1]] <=> dists[b[0]][b[1]]}
    q.delete(u)

    um, ubits = u
    break if um == 0 && ubits == allbits

    ud = dists[um][ubits]

    for vm in nbrs[um]
      vbits = ubits | pbits[vm]
      vd = dists[vm][vbits]
      nd = ud + edges[um][vm]
      if vd > nd
        dists[vm][vbits] = nd
        if vd >= MAX_INT
          q << [vm, vbits]
        end
      end
    end
  end

  puts [sumval, dists[0][allbits]].join(' ')
end

Measured memory_bytes: 9116
import java.util.*;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		long nn = sc.nextLong();
		long tmp=0;
		long min_num = nn;
		
		for(long i=2;i<=Math.sqrt(nn);i++){
			if(nn%i==0){
				tmp = (long)nn/i;
				if((tmp+i)<min_num){
					min_num = tmp+i;
				}
			}
		}
		
		if(tmp==0){
			System.out.print(nn-1);
		}else{
			System.out.print(min_num-2);
		}
	}	
}

Measured memory_bytes: 23124
MOD = 1000000007
n, m = map(int,input().split())
xlst = list(map(int, input().split()))
ylst = list(map(int, input().split()))
xs = 0
for i in range(n - 1):
    w = xlst[i + 1] - xlst[i]
    xs += w * (i + 1) * (n - i - 1)
    xs %= MOD
ys = 0
for i in range(m - 1):
    h = ylst[i + 1] - ylst[i]
    ys += h * (i + 1) * (m - i - 1)
    ys %= MOD
print(xs * ys % MOD)

Measured memory_bytes: 18556
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<iomanip>
#include<queue>
#define maxn 1000003
using namespace std;
struct A{
	char color[maxn];
	int num;
};
char tcolor[maxn] = {0};
int main(){
	A a[2];
	for(int i = 0; i < 2; i++){
		cin >> a[i].color;
	}
	for(int i = 0; i < 2; i++){
		cin >> a[i].num;
	}
	cin >> tcolor;
	for(int i = 0; i < 2; i++){
		if(strcmp(a[i].color,tcolor)==0){
			a[i].num--;
			break;
		}
	}
	cout << a[0].num << " " << a[1].num << endl;
	return 0;
} 

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <deque>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cassert>
#include <chrono>
#include <random>
#include <limits>
#include <iterator>
#include <functional>
#include <sstream>
#include <complex>
using namespace std;

using ll = long long;
using ull = uint64_t;
using P = pair<int, int>;
constexpr double EPS = 1e-9;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
// constexpr int mod = 998244353;

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

struct Timer{
    chrono::high_resolution_clock::time_point st;

    Timer() { reset(); }

    void reset(){
        st = chrono::high_resolution_clock::now();
    }

    chrono::milliseconds::rep elapsed(){
        auto ed = chrono::high_resolution_clock::now();
        return chrono::duration_cast<chrono::milliseconds>(ed - st).count();
    }
};

struct RNG{
    mt19937 mt;

    RNG() : mt(chrono::steady_clock::now().time_since_epoch().count()){}

    int operator()(int a, int b){
        uniform_int_distribution<int> dist(a, b - 1);
        return dist(mt);
    }

    int operator()(int b){
        return (*this)(0, b);
    }
};

constexpr int D = 365;
vector<int> c(26);
vector<vector<int>> s(D, vector<int>(26));
Timer TimeKeeper;
RNG rng;
constexpr ll inf = 1e+15;

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

    int kyomu;
    cin >> kyomu;
    for(int i = 0; i < 26; ++i) cin >> c[i];
    vector<int> maxe(D, -1);
    vector<int> cur(D, 0);
    for(int i = 0; i < D; ++i){
        for(int j = 0; j < 26; ++j){
            cin >> s[i][j];
            if(chmax(maxe[i], s[i][j])) cur[i] = j;
        }
    }

    ll BestScore = 0;
    auto calc_score = [&](vector<int>& v) -> ll {
        ll res = 0;
        vector<int> pre(26, -1);
        for(int i = 0; i < D; ++i){
            res += s[i][v[i]];
            pre[v[i]] = i;
            for(int j = 0; j < 26; ++j){
                res -= c[j] * (i - pre[j]);
            }
        }
        return res;
    };
    BestScore = calc_score(cur);

    int Day = 0;
    while(TimeKeeper.elapsed() < 1985){
        ll NxtScore = -inf;
        int ProblemType = -1;
        vector<int> nxt = cur;
        for(int i = 0; i < 26; ++i){
            if(i == cur[Day])   continue;
            nxt[Day] = i;
            if(chmax(NxtScore, calc_score(nxt)))    ProblemType = i;
        }
        if(chmax(BestScore, NxtScore)){
            cur[Day] = ProblemType;
        }
        if(++Day == D)  Day = 0;
    }
    cerr << BestScore << endl;

    for(int i = 0; i < D; ++i)  cout << cur[i] + 1 << '\n';
}

Measured memory_bytes: 3252
#include <stdio.h>
#include <string.h>
 
#define MAX(a,b) ((a)>(b)?(a):(b))
#define MIN(a,b) ((a)<(b)?(a):(b))
#define ABS(a) ((a)>(0)?(a):-(a))

typedef long long int int64;
typedef unsigned char uchar8;

#define MAX_W 2000
#define MAX_H 2000

uchar8 S[MAX_H][MAX_W];

int spW[MAX_H];
int spH[MAX_W];

int H = 0;
int W = 0;

int sp_N(int w, int h) {
  int cnt_sp = 0;
  int x,y;
  static int cache_spN[MAX_H][MAX_W] = {0,};

  x = w;

  if ((h > 0) &&
      (cache_spN[h-1][w] > 0)) {
    if (S[h][w] != 1) {
      cache_spN[h][w] = cache_spN[h-1][w] + 1;
      return cache_spN[h][w];
    }
  }
  
  for (y=h; y>=0; y--) {
    if (S[y][x] == 1) {
      break;
    }
    cnt_sp++;
  }

  cache_spN[h][w] = cnt_sp;
  
  return cnt_sp;
}

int sp_S(int w, int h) {
  int cnt_sp = 0;
  int x,y;
  static int cache_spS[MAX_H][MAX_W] = {0,};

  x = w;

  if ((h < (H - 1)) &&
      (cache_spS[h + 1][w] > 0)) {
    if (cache_spS[h][w] != 1) {
      cache_spS[h][w] = cache_spS[h + 1][w] + 1;
    }
  }
  
  for (y=h; y<H; y++) {
    if (S[y][x] == 1) {
      break;
    }
    cnt_sp++;
  }
  cache_spS[h][w] + cnt_sp;
    
  return cnt_sp;
}

int sp_W(int w, int h) {
  int cnt_sp = 0;
  int x,y;
  static int cache_spW[MAX_H][MAX_W] = {0,};

  y = h;

  if ((w > 0) &&
      (cache_spW[h][w - 1] > 0)) {
    if (S[h][w] != 1) {
      cache_spW[h][w] = cache_spW[h][w - 1] + 1;
      return cache_spW[h][w];
    }
  }
  
  for (x=w; x>=0; x--) {
    if (S[y][x] == 1) {
      break;
    }
    cnt_sp++;
  }

  cache_spW[h][w] = cnt_sp;
  
  return cnt_sp;
}

int sp_E(int w, int h) {
  int cnt_sp = 0;
  int x,y;

  y = h;
  for (x=w; x<W; x++) {
    if (S[y][x] == 1) {
      break;
    }
    cnt_sp++;
  }
  
  return cnt_sp;
}

int main()
{

  int cnt;
  int i,j;
  int cnt_sp;
  int max_sp = 0;
  char str[MAX_W];
 

  cnt = scanf("%d %d", &H, &W);

  for (i=0; i<H; i++) {
   cnt = scanf("%s", (char *)(str));
    str[W]= 0x1;
    for(j=0; j<W; j++) {
      if(str[j] == '#') {
        S[i][j] = 1;
      } else {
        S[i][j] = 0;
      }
    }
  }

  for (i=0; i<H; i++) {
    for (j=0; j<W; j++) {
      if (S[i][j] != 0) continue;
      cnt_sp = 0;
      cnt_sp += sp_N(j,i);
      if (MAX(max_sp, (cnt_sp - 1 + W + (H-j))) == max_sp) continue;
      cnt_sp += sp_S(j,i);
      if (MAX(max_sp, (cnt_sp + W - 2)) == max_sp) continue;
      cnt_sp += sp_W(j,i);
//      if (MAX(max_sp, (cnt_sp - 2 + (W-i))) == max_sp) continue;
      cnt_sp += sp_E(j,i);
      cnt_sp -= 3;
      max_sp = MAX(max_sp, cnt_sp);
    }
  }

  printf(" %d", max_sp);
  
  return 0;
}


Measured memory_bytes: 36608
import java.util.Scanner;

public class Main {
    private static final int MOD = 1_000_000_007;
    private static final String YES = "Yes";
    private static final String NO = "No";

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int[] A = new int[N];
        for (int i=0; i<N-1; i++) {
            A[i] = sc.nextInt();
        }

        int[] ans = solve(N, A);
        for (int i=0; i<N; i++) {
            System.out.println(ans[i]);
        }
    }

    private static int[] solve(int N, int[] A) {
        int[] ans = new int[N];

        for (int i=0; i<N-1; i++) {
            ans[A[i]-1]++;
        }

        return ans;
    }
}

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

using namespace std;
typedef long long ll;
//#include <boost/multiprecision/cpp_int.hpp>
//typedef boost::multiprecision::cpp_int ll;
typedef long double dd;

#define i_7 (ll)(1E9+7)
//#define i_7 998244353
#define i_5 i_7-2
ll mod(ll a){
    ll c=a%i_7;
    if(c>=0)return c;
    return c+i_7;
}
 
typedef pair<ll,ll> l_l;
ll inf=(ll)1E16;
#define rep(i,l,r) for(ll i=l;i<=r;i++)
#define pb push_back
ll max(ll a,ll b){if(a<b)return b;else return a;}
ll min(ll a,ll b){if(a>b)return b;else return a;}

void Max(ll &pos,ll val){pos=max(pos,val);}//Max(dp[n],dp[n-1]);
void Min(ll &pos,ll val){pos=min(pos,val);}
void Add(ll &pos,ll val){pos=mod(pos+val);}
dd EPS=1E-9;
#define fastio ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define fi first
#define se second
////////////////////////////

bool comp(l_l a,l_l b){
    return a.second<b.second;
}

int main(){fastio
    vector<l_l>v;
    ll n;cin>>n;
    rep(i,1,n){
        ll a,b;cin>>a>>b;
        ll c=a-b,d=a+b;
        v.pb(l_l(c,d));
    }
    sort(v.begin(),v.end(),comp);
    ll ans=1;
    ll pos=v[0].second;
    rep(i,1,n-1){
        if(pos<=v[i].first){
            ans++;
            pos=v[i].second;
        }
    }
    cout<<ans<<endl;
    return 0;
}


Measured memory_bytes: 2420
#include <bits/stdc++.h>
typedef long long ll;
#define FOR(i,a,b) for(ll i=(a);i<(b);i++)
#define REP(i,a) FOR(i,0,a)
using namespace std;
const ll MAX_N=50;

ll N;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>N;
    ll c=0;
    REP(i,N){
        ll p;
        cin>>p;
        if(p!=i+1){
            c++;
        }
    }
    cout<<(c<=2 ? "YES":"NO")<<endl;
}

Measured memory_bytes: 256