akhauriyash/Code-Regression huggingface dataset:
require 'set'

Move = [ [1, 3], [0, 2, 4], [1, 5],
         [0, 4, 6], [1, 3, 5, 7], [2, 4, 8],
         [3, 7], [4, 6, 8], [5, 7] ]

R = [0, 0, 0, 1, 1, 1, 2, 2, 2]
C = [0, 1, 2, 0, 1, 2, 0, 1, 2]

def min_heapify(x = 1)
  l = 2*x
  r = 2*x+1
  if l <= $n && $heap[l][0] < $heap[x][0]
    minimum = l
  else
    minimum = x
  end
  if r <= $n && $heap[r][0] < $heap[minimum][0]
    minimum = r
  end
  if minimum != x
    $heap[x], $heap[minimum] = $heap[minimum], $heap[x]
    min_heapify(minimum)
  end
end

def extract
  key = $heap[1]
  $heap[1] = $heap[$n]
  $n -= 1
  min_heapify
  key
end

def insert(key)
  $n += 1
  $heap[$n] = key
  i = $n
  while i > 1 && $heap[i/2][0] > $heap[i][0]
    $heap[i], $heap[i/2] = $heap[i/2], $heap[i]
    i /= 2
  end
end

def judge(brd, c)
  ret = c
  9.times do |i|
    if brd[i] > 0
      [R, C].each do |a|
        ret += (a[i] - a[brd[i] - 1]).abs
      end
    end
  end
  ret
end

brd = 3.times.map{ gets.split.map(&:to_i) }.flatten
$heap = []
$n = 0
insert [judge(brd, 0), brd, 0]
set = SortedSet.new([])
set.add(brd)
while $n > 0
  val, b, cnt = extract
  next if val > 45
  if val == cnt
    p cnt
    break
  end
  n = b.index(0)
  Move[n].each do |m|
    b[n], b[m] = b[m], b[n]
    nb = b.dup
    unless set.include?(nb)
      set.add(nb)
      insert [judge(b, cnt+1), nb, cnt + 1]
    end
    b[n], b[m] = b[m], b[n]
  end
end

Measured memory_bytes: 13060
import math
n,m=map(int,input().split())
M=max(n,m)
mm=min(n,m)
if M-mm>1:
    ans=0
else:
    if n==m:
        ans=2*math.factorial(n)**2
    else:
        ans=M*math.factorial(mm)**2
print(ans%(1000000007))

Measured memory_bytes: 4748
import Control.Applicative
import Data.Fixed

main = do
    r <- (read :: String -> Double) <$> getLine
    putStrLn $ unwords $ show . toFixedE9 <$> [(pi*r^2), (2*pi*r)]

toFixedE9 :: Double -> Fixed E9
toFixedE9 r = realToFrac r :: Fixed E9

Measured memory_bytes: 4056
#!/usr/bin/env python3

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())
    
    
    n, m = mi()
    l_list = []
    r_list = []
    for _ in range(m):
        l, r = mi()
        l_list.append(l)
        r_list.append(r)
    print(max(min(r_list)-max(l_list)+1, 0))

if __name__ == "__main__":
    main()

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

int main() {
	int n; cin >> n;
	string s; cin >> s;
	bool flag[100]; for (int i = 0; i < 100; i++)flag[i] = false;
	
	int left = 0, right = 0;
	for (int i = 0; i < n; i++) {
		if (flag[i])continue;
		bool ok = false;
		if (s[i] == '(') {
			for (int j = i + 1; j < n; j++) {
				if (!flag[j] && s[j] == ')') {
					ok = flag[i] = flag[j] = true;
					break;
				}
			}
			if (!ok)right++;
		}
		else {
			for (int j = i - 1; j >= 0; j--) {
				if (!flag[j] && s[j] == '(') {
					ok = flag[i] = flag[j] = true;
					break;
				}
			}
			if (!ok)left++;
		}
	}
	for (int i = 0; i < left; i++)cout << '(';
	cout << s;
	for (int i = 0; i < right; i++)cout << ')';
	cout << endl;

	return 0;
}

Measured memory_bytes: 256
def main():
    N,W = map(int,input().split())
    wv = [list(map(int,input().split())) for _ in range(N)]
    dp = [[0]*(W+1) for _ in range(N+1)]
    for i in range(N):
        for j in range(W+1):
            if j-wv[i][0] >= 0:
                dp[i+1][j] = max(dp[i][j],dp[i][j-wv[i][0]]+wv[i][1])
            else:
                dp[i+1][j] = dp[i][j]
    print(dp[N][W])

if __name__ == '__main__':
    main()

Measured memory_bytes: 120304
while True:
    m,f,r = map(int,input().split())
    score = m + f

    if m==-1 and f==-1 and r==-1:
        break
    elif m==-1 or f==-1:
        print("F")
    elif score>=80:
        print("A")
    elif score>=65:
        print("B")
    elif score>=50:
        print("C")
    elif score>=30:
        if r>=50:
            print("C")
        else:
            print("D")
    else:
        print("F")





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

int lis(vector<int> a) {
	// longest increasing subsequence
	// o(n logn)
	vector<int> v(a.size()+1, -1);
	int l = 0;
	for (int unsigned i = 0; i < a.size(); i++) {
		if (v[l] < a[i]) {
			v[++l] = a[i];
		}
		else {
			*lower_bound(v.begin(), v.begin() + l, a[i]) = a[i];
		}
	}
	return l;
}

int main() {
	int n;
	cin >> n;
	vector<int> v(n);
	for (int i = 0; i < n; i++) {
		cin >> v[i];
	}
	cout << lis(v) << endl;
	return 0;
}

Measured memory_bytes: 3960
import java.util.Scanner;
public class Main{
	private static Scanner sc=new Scanner(System.in);
	public static void  main(String[]agrs){
		int a[][]=new int[14][14];
		while(sc.hasNext()){
			String m=sc.nextLine();
			String[] mm=m.split(",");
			int x=Integer.parseInt(mm[0]);
			int y=Integer.parseInt(mm[1]);
			int size=Integer.parseInt(mm[2]);
			int kx=x+2;
			int ky=y+2;
			a[kx][ky]++;
			a[kx+1][ky]++;
			a[kx][ky+1]++;
			a[kx-1][ky]++;
			a[kx][ky-1]++;
			if(size>=2){
				a[kx+1][ky+1]++;
				a[kx-1][ky+1]++;
				a[kx+1][ky-1]++;
				a[kx-1][ky-1]++;
			}
			if(size>=3){
				a[kx+2][ky]++;
				a[kx-2][ky]++;
				a[kx][ky+2]++;
				a[kx][ky-2]++;
			}
		}
		int cnt0=0;
		int max=0;
		for(int i=2;i<12;i++){
			for(int j=2;j<12;j++){
				if(a[i][j]==0)cnt0++;
				if(a[i][j]>max)max=a[i][j];
			}
		}
		System.out.println(cnt0);
		System.out.println(max);


	}
}

Measured memory_bytes: 25728
import java.util.*;

public class Main {
    public static void main(String[] args) {
        try(Scanner sc = new Scanner(System.in)) {
            int N = sc.nextInt();
            int M = (int)Math.floor(N/2);
            int answer = Integer.MAX_VALUE;
            for ( int A = 1; A <= M; A++ ) {
                int B = N - A;
                int candidate = digitSum(A) + digitSum(B);
                if ( candidate < answer ) {
                    answer = candidate;
                }
            }
            System.out.println(answer);
        }
    }

    private static int digitSum(int n) {
        if ( n < 10 ) {
            return n;
        }
        else {
             int r = n % 10;
             int q = (n-r)/10;
             return r + digitSum(q);
        }
    }
}

Measured memory_bytes: 23124
#include <iostream>

using namespace std;

int main(void) {

	int A, B, C, D = 0;

	cin >> A;
	cin >> B;
	cin >> C;
	cin >> D;

	int Takahashi = 0;
	int Aoki = 0;

	Takahashi = A;
	Aoki = C;

	int winFlg = 0; //1:Takahasi Win, 2:Aoki Win

	while ( ( Takahashi > 0 ) && ( Aoki > 0 ) ) {

		Aoki = Aoki - B;
		if( Aoki <= 0 ) {
			winFlg = 1;
			break;
		}

		Takahashi = Takahashi - D;
		if( Takahashi <= 0 ) {
			winFlg = 2;
			break;
		}

	}

	if( winFlg == 1 ) {
		cout << "Yes";
	}
	else {
		cout << "No";
	}

	return 0;
}

Measured memory_bytes: 3572
import java.util.Scanner;
public class Main{
    public static void main(String args[]){
        Scanner scan=new Scanner(System.in);
        String str=scan.next();
        int l,i;
        while(str.length()!=2){
            l=str.length();
            str=str.substring(0,l-2);
           // System.out.println(str);
            l=str.length();
            for(i=0;i<l/2;i++){
                if(str.charAt(i)!=str.charAt(l/2+i)){
                    break;
                }
                else if(i==l/2-1){
                    System.out.println(l);
                    return;
                }
            }
        }
    }
}

Measured memory_bytes: 23636
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include <complex>
#include <ctime>
#include <cassert>
#include <functional>
#include <list>
#include <bitset>
#include <cfenv>
#include <numeric>
#include <utility>
#include <cstdio>
#include <fstream>
#include <deque>
#include <limits>
#include <climits>
using namespace std;
typedef pair<int, int> ii;

int main() {
    ios::sync_with_stdio(false);

    string input, xS,yS, sizeS;
    int x, y, size;

    int grid[20][20];
    memset(grid, 0, sizeof(grid));

    while(getline(cin, input)) {

        // parse
        xS = input.substr(0, input.find_first_of(','));
        yS = input.substr(input.find_first_of(',') + 1, input.find_last_of(',') - input.find_first_of(','));
        sizeS = input.substr(input.find_last_of(',') + 1, input.size());

        stringstream parser;
        parser.str(xS);
        parser >> x;
        parser.clear();
        parser.str(yS);
        parser >> y;
        parser.clear();
        parser.str(sizeS);
        parser >> size;

        x += 5;
        y += 5;

        // simulate grid

        switch ( size ) {

                // large
            case 3: {
                // outer edges
                grid[x + 2][y]++;
                grid[x - 2][y]++;
                grid[x][y + 2]++;
                grid[x][y - 2]++;
            }
               //medium
            case 2: {

                // outer corners
                grid[x - 1][y - 1]++;
                grid[x + 1][y + 1]++;
                grid[x - 1][y + 1]++;
                grid[x + 1][y - 1]++;
            }
                // small
            case 1: {
                // cross shaped
                grid[x][y]++;
                grid[x - 1][y]++;
                grid[x + 1][y]++;
                grid[x][y - 1]++;
                grid[x][y + 1]++;
                break;
            }

        }
    }

    // find densest spot and number of clear spots
    int densest = 0;
    int clear = 0;

    for(int i = 5; i <= 14; i++) {
        for(int j = 5; j <= 14; j++) {
            if(grid[i][j] > densest)
                densest = grid[i][j];
            else if(grid[i][j] == 0)
                clear++;
        }
    }

    cout << clear << endl;
    cout << densest << endl;
    return 0;
}

Measured memory_bytes: 1220
from collections import defaultdict

N, K, Q = map(int, input().split())

num_correct = defaultdict(int)

for _ in range(Q):
  answerer = int(input()) - 1  # index に直す
  num_correct[answerer] += 1  
                                  
for i in range(N):
  if K - Q + num_correct[i] > 0:
    print('Yes')
  else:
    print('No')
                 

Measured memory_bytes: 16156
N, X = map(int, input().split())
L = [int(x) for x in input().split()]

cnt = 1
position = 0
for i in range(min(len(L), N)):
    distance = L[i]
    position += distance
    if position <= X:
        cnt += 1
        continue
    else:
        break

print(cnt)


Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
#define LLINF 9223372036854775807
#define MOD ll(1e9+7)

vector<pii> most_common(const map<int,int> &mp){
    vector<pii> v;
    for(auto itr = mp.begin(); itr != mp.end(); ++itr) {
        v.push_back({itr->first,itr->second});
    }

    sort(v.begin(), v.end(), [](const pii &x,const pii &y){return x.second>y.second;});
    return v;
}

int main(){
    int n;
    cin >> n;
    vector<int> a(n), even(n/2), odd(n/2);
    map<int,int> am, evenm, oddm;
    for(int i = 0; i < n; i++){
        cin >> a[i];
        am[a[i]]++;
    }

    for(int i = 0; i < n; i++){
        if(i%2==1){
            even[i/2] = a[i];
            evenm[a[i]]++;
        }
        else{
            odd[i/2] = a[i];
            oddm[a[i]]++;
        }
    }
    if(am.size()==1){
        cout << n/2 << endl;
        return 0;
    }

    vector<pii> evenmc = most_common(evenm);
    vector<pii> oddmc = most_common(oddm);

    if(evenmc[0].first == oddmc[0].first){
        if(evenm.size()==1){
            int ans = odd.size() - oddmc[1].second;
            cout << ans << endl;
            return 0;
        }
        if(oddm.size()==1){
            int ans = even.size() - evenmc[0].second;
            cout << ans << endl;
            return 0;
        }

        int ans1 = n - evenmc[0].second - oddmc[1].second;
        int ans2 = n - evenmc[1].second - oddmc[0].second;
        cout << min(ans1,ans2) << endl;
        return 0;

    }else{
        int ans = n - evenmc[0].second - oddmc[0].second;
        cout << ans << endl;
        return 0;
    }

}


Measured memory_bytes: 11516
import sys
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

S, T = SR(2)

counter = 0
for i in range(len(S)):
    if S[i] != T[i]:
        counter += 1

print(counter)

Measured memory_bytes: 9624
<?php
  
  fscanf(STDIN,"%d%d",$n,$k);
$a_li = explode(" ",trim(fgets(STDIN)));
$syurui=array();
foreach($a_li as $a){
  $syurui[$a]++;
}


sort($syurui);
//print_r($syurui);
$c=0;
$i=0;
while(count($syurui)-$i>$k){
  $c+=$syurui[$i];
  $i++;
}

echo $c;
    

Measured memory_bytes: 35312
n = int(input())
list_a = [int(x) for x in input().split()]

sum = 0
ans_even = 0
ans_odd = 0

for i in range(n) :
    sum += list_a[i]
    if i%2 == 0 :
        if sum <= 0 :
            ans_even += abs(sum) + 1
            sum = 1
    else :
        if sum >= 0 :
            ans_even += abs(sum) + 1
            sum = -1

sum = 0

for i in range(n) :
    sum += list_a[i]
    if i%2 == 1 :
        if sum <= 0 :
            ans_odd += abs(sum) + 1
            sum = 1
    else :
        if sum >= 0 :
            ans_odd += abs(sum) + 1
            sum = -1

print(min(ans_even, ans_odd))


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

typedef long long LL;

const int N = 18;
const LL inf = 0x3f3f3f3f3f3f3f3f;
int n, a[N];
LL dp[N + 1][N + 1][1 << N], ans;

LL dfs(int l, int r, int u, int v, int status) {
	if (l > r) return 0;
	if (l == r) return (LL) a[l] * (u + v);
	if (~dp[l][r][status]) return dp[l][r][status];
	LL &ret = dp[l][r][status] = inf;
	for (int p = l; p <= r; ++p)
		ret = std::min(ret, dfs(l, p - 1, u, u + v, status << 1) + 
							dfs(p + 1, r, u + v, v, status << 1 | 1) + (LL) a[p] * (u + v));
	return ret;
}

int main() {
	std::ios::sync_with_stdio(0), std::cin.tie(0);
	std::memset(dp, -1, sizeof dp);
	std::cin >> n >> ans, n -= 2;
	for (int i = 0; i <= n; ++i) std::cin >> a[i];
	ans += a[n];
	std::cout << dfs(0, n - 1, 1, 1, 1) + ans << '\n';
	return 0;
}

Measured memory_bytes: 739584
#include <iostream>
#define a_MAX 100000
using namespace std;

long long ary[a_MAX+1];

int main(void){
    int N;  long long K;
    cin >> N >> K;

    int a, b;
    for(int i=0; i<N; i++){
        cin >> a >> b;
        ary[a] += b;
    }

    long long ans = 0;
    for(int i=1; ans<K && i<=a_MAX; i++){
        ans += ary[i];
        if(ans>=K){
            cout << i << '\n';
            break;
        }
    }

    return 0;
}


Measured memory_bytes: 1024
#include "bits/stdc++.h"
#define ll long long
#define ALL(x) x.begin(),x.end()
#define MOD (1000000000+7)
using namespace std;

int main(){
ll N;
cin>>N;

ll tmp=0;
for(ll i=1;i<=9;i++){
  if(N%i==0){
    if(1<=N/i&&N/i<=9){
      tmp=1;
    }
  }
}
if(tmp==1){
  cout<<"Yes"<<endl;
}
else
{
  cout<<"No"<<endl;
}


}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <vector>
#include <math.h>
#include <cstdlib>
#include <cctype>
using namespace std;

int main() {
    string S;
    cin >> S;
    int Si;
    Si = stoi(S);

    if (Si / 100 > 12 || Si / 100 == 0) {
        if (Si % 100 > 12 || Si % 100 == 0) {
            cout << "NA" << endl;
        } else {
            cout << "YYMM" << endl;
        }
    } else {
        if (Si % 100 > 12 || Si % 100 == 0) {
            cout << "MMYY" << endl;
        } else {
            cout << "AMBIGUOUS" << endl;
        }
    }

    return 0;
}


Measured memory_bytes: 760
#include <bits/stdc++.h>
using namespace std;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)
#define ALLOF(c) (c).begin(), (c).end()
typedef long long ll;
typedef unsigned long long ull;

vector<int> G[55];

int main(){
  int N, M;
  cin >> N >> M;
  rep(i,M){
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    G[a].push_back(b);
    G[b].push_back(a);
  }

  rep(i,N){
    cout << G[i].size() << endl;
  }
  
  return 0;
}


Measured memory_bytes: 256
// finish date: 2018/01/21
#include <iostream>
#include <cmath>
#include <vector>
#include <bitset>
#include <algorithm>
#include <stack>
#include <map>
#include <climits>

using namespace std;

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


int main() {
    int A, B;
    string S;
    cin >> A >> B >> S;
    if (S.length() != A + B + 1) {
        cout << "No" << endl;
        return 0;
    }
    rep(i, S.length()) {
        if (i == A) {
            if (S[i] != '-') {
                cout << "No" << endl;
                return 0;
            }
        } else {
            if (!('0' <= S[i] && S[i] <= '9')) {
                cout << "No" << endl;
                return 0;
            }
        }
    }
    cout << "Yes" << endl;

    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define rep(i,N) for(ll (i)=0;(i)<(N);(i)++)
#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int mod = 1000000007;
const int INF = 1001001001;
bool hantei (int x) {
  while (x > 0) {
    if (x % 10 != 7) {
      return false;
    }
    x /= 10;
  }
  return true;
}

bool getlen (int x) {
  int res = 0;
  while (x > 0) {
    res++;
    x /= 10;
  }
  return res;
}

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

  int ans = 0;
  int pre = 0;

  while (1) {
    bool dame = true;
    rep(i, 10) {
      int val = i * k + pre;
      if (val % 10 == 7) {
        dame = false;
        ans++;
        val /= 10;
        pre = val;
        break;
      }
    }
    if (dame) {
      cout << -1 << endl;
      return 0;
    }

    if(hantei(pre)) {
      while (pre > 0) {
        ans++;
        pre /= 10;
      }
      cout << ans << endl;
      return 0;
    };
  }

}

Measured memory_bytes: 3576
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define size 400
#define ll long long int
ll arr[size];
int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
		cin>>arr[i];
	ll dp[n][n];
	for(int t=0;t<n;t++)
	{
		for(int j=t;j<n;j++)
		{
			int i=j-t;
			if(j==i)
				dp[i][j]=0;
			else 
			{
				ll min=LONG_MAX;
				ll sum=0;
				for(int k=i;k<j;k++)
				{
					if(dp[i][k]+dp[k+1][j]<min)
					{
						min=dp[i][k]+dp[k+1][j];
					}
					sum+=arr[k];
				}
				dp[i][j]=min+sum+arr[j];
			}
		}
	}
	cout<<dp[0][n-1]<<endl;
}

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

namespace prog
{
    class Source
    {
        static void Main()
        {
            int N = int.Parse(Console.ReadLine());
            int[] dp = new int[100010];
            dp[0] = 0;
            int x = 1;
            for (int i = 1; i <= N; i++)
            {
                dp[i] = dp[i - 1] + 1;
                for (int j = 1; j < 10; j++)
                {
                    x = (int)Math.Pow(6, j);
                    if (x > i) break;
                    dp[i] = Math.Min(dp[i], dp[i - x] + 1);
                }
                for (int j = 1; j < 10; j++)
                {
                    x = (int)Math.Pow(9, j);
                    if (x > i) break;
                    dp[i] = Math.Min(dp[i], dp[i - x] + 1);
                }
            }
            Console.WriteLine(dp[N]);
        }
    }
}


Measured memory_bytes: 11360
S = list(map(int, list(input())))

pops = 0
digi = 1
cnt = [0] * 2019
cnt[0] = 1

while S:
    s = S.pop()

    pops = (pops + s * digi) % 2019
    digi = (10 * digi) % 2019

    cnt[pops] += 1

ans = 0

for i in range(2019):
    ans += cnt[i] * (cnt[i] - 1) // 2

print(ans)

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

#define MP make_pair
#define FF first
#define SS second
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pie;
const int MOD = 1e9 + 7;
const int INF = 2e9;
const ll LINF = 4e18;
const ll delta = 96181;

const int N = 1e5 + 20;
vector<int> G[N];
int n, dp[N];

void dfs(int v, int p = -1) {
	int mx = 0, cnt = 0;
	for (int u : G[v])
		if (u - p) {
			dfs(u, v);
			if (dp[u])
				cnt++;
			dp[v] += dp[u];
		}
	if (p + 1)
		dp[v] += max(0, (int)G[v].size() - 2 - cnt);
	else
		dp[v] += max(0, (int)G[v].size() - 1 - cnt);
}

int main() {
	ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n;
	for (int i = 0, v, u; i < n - 1; i++) {
		cin >> v >> u;
		G[v].push_back(u);
		G[u].push_back(v);
	}
	int root = -1;
	for (int i = 0; i < n; i++)
		if (G[i].size() > 2)
			root = i;
	if (root == -1)
		return cout << 1 << endl, 0;
	dfs(root);
	cout << dp[root] << endl;
}



Measured memory_bytes: 10496
#include <iostream>
#include <iosfwd>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cassert>
#include <cctype>
#include <climits>
#include <vector>
#include <bitset>
#include <set>
#include <queue>
#include <math.h>
#include <stack>
#include <map>
#include <deque>
#include <string>
#include <list>
#include <iterator>
#include <sstream>
#include <complex>
#include <fstream>
#include <functional>
#include <numeric>
#include <utility>
#include <algorithm>
#include <assert.h>
#include <unordered_map>
#pragma GCC optimize ("-O3")
using namespace std;
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cerr.tie(NULL);
#define tolower(s) transform(s.begin(),s.end(),s.begin(),::tolower);
#define toupper(s) transform(s.begin(),s.end(),s.begin(),::toupper);
#define ll long long int
ll max(ll a, ll b) {  return a > b ? a : b; }
ll gcd(ll a, ll b) { if (a == 0) return b; return b == 0 ? a : gcd(b, a % b);}
#define case(i) cout<<"Case #"<<i<<": ";
#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); cerr << '\n'; }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
#define debug2(...) fprintf(stderr, __VA_ARGS__), fflush(stderr)
void err(istream_iterator<string> it, T a, Args... args) { cerr << "[ " << *it << " = " << a << " ]"; err(++it, args...);}
#define time__(d) for (auto blockTime = make_pair(chrono::high_resolution_clock::now(), true); blockTime.second; debug2("%s: %lld ms\n", d, chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - blockTime.first).count()), blockTime.second = false)
#define pii pair <ll , ll >
#define pb push_back
#define PRECISION 10
const ll inf = 9223372036854775800;
const int MAXN = 100001;
const int LOGN = 22;
const int MAXBIT = 62;
const long double PI = 3.141592653589793;
const int DIGITSIZE = 18;
ll mod = 1e9 + 7;
ll MOD = 998244353;
int x4[] = {1, -1, 0, 0};
int y4[] = {0, 0, 1, -1};
int x8[] = {1, 1, 1, -1, -1, -1, 0, 0};
int y8[] = {1, 0, -1, 1, 0, -1, 1, -1};
bool takeTestCases = 0;
bool printCaseNo = 0;

void getac(int T) {
    int n;
    cin >> n;
    int arr[n];
    int hash1[1000001];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    memset(hash1, 0, sizeof(hash1));
    int ans1 = 0;
    for (int i = 0; i < n; i++) {
        if (hash1[arr[i]] > 1) {
            continue;
        }
        bool ans = true;
        for (int j = arr[i]; j <= 1e6; j += arr[i]) {
            hash1[j]++;
        }

    }
    for (int i = 0; i < n; i++) {
        if (hash1[arr[i]] > 1) {

        } else {
            ans1++;
        }
    }
    cout << ans1 << '\n';
}
int  main()
{

    fastio;
    int t = 1;
    if (takeTestCases) cin >> t;
    int t_t = 1;
    while (t--) {
        if (printCaseNo)
        case (t_t);

        getac(t_t);
        t_t++;
    }
    cerr << "Total time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
    return 0;
}


Measured memory_bytes: 8496
#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <vector>

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

int main(){
  int a,b;
  cin >> a >> b;
  cout << (a-1)*(b-1) << endl;
}


Measured memory_bytes: 256
#include <stdio.h>
int main (){
    char s[4];
    int i;
    int sum = 0;
    scanf("%s", s);
    for (i = 0; i < 4; i++){
        if (s[i] == '+') sum++;
        if (s[i] == '-') sum--;
    }
    printf("%d",sum);
    return 0;
}

Measured memory_bytes: 128
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LS()
    return l
sys.setrecursionlimit(1000000)
mod = 1000000007

#A
def A():
    p,q,r = LI()
    print(p+q+r-max(p,q,r))
    return

#B
def B():
    n = I()
    w = LI()
    ans = float("inf")
    for i in range(n):
        m = sum(w[:i])
        l = sum(w[i:])
        ans = min(ans,abs(m-l))
    print(ans)
    return

#C
def C():
    n,m = LI()
    f = [1 for i in range(n+1)]
    for i in range(m):
        a = I()
        f[a] = 0
    dp = [0 for i in range(n+1)]
    dp[0] = 1
    for i in range(1,n+1):
        if f[i]:
            dp[i] = dp[i-1]+dp[i-2]
            dp[i] %= mod
    print(dp[n])
    return

#D
def D():
    h,w = LI()
    s = SR(h)

    return

#E
def E():
    n = I()

    return

#F
def F():
    n = I()

    return

#Solve
if __name__ == "__main__":
    C()


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

typedef long long ll;

int main(void) {
	ll N, P;
	cin >> N >> P;

	vector<ll> A(N);
	ll even=0;
	for (int i = 0; i < N; i++){
	    cin >> A[i];
	    if(A[i]%2==0)even++;
	}
    
    ll ans;
    if(even==N){
        if(P) ans = 0;
        else ans = pow(2LL, N);
    }else{
	    ans = pow(2LL, N - 1);
    }
	cout << ans << endl;
}

Measured memory_bytes: 256
def d():
    n = int(input())
    ls = list(map(int, input().split()))
    ls.sort()
    count = 0
    for i in range(n-1):
        k = i + 2
        for j in range(i+1, n-1):
            while k < n and ls[i] + ls[j] > ls[k]:
                k += 1
            count += k - j - 1

    print(count)


if __name__ == '__main__':
    d()


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

using ll = long long;
#define debug(x) cerr << #x << ": " << x << endl;
#define line() cerr << "---------------" << endl;

int H, W;
const int dx[] = {0, 0, -1, 1};
const int dy[] = {1, -1, 0, 0};
char land[105][105];

// @:リンゴ, #:カキ, *:ミカン, 0:visited
void dfs(int y, int x,char c) {
	land[y][x] = '0';
	for (int i = 0; i < 4; i++) {
		int ny = y+dy[i], nx = x+dx[i];
		if (ny >= 0 && ny < H && nx >= 0 && nx < W && land[ny][nx] == c) {
			dfs(ny, nx, c);
		}
	}
	return;
}

int main() {
	while (cin >> H >> W) {
		if (H == 0 && W == 0) break;
		for (int i = 0;  i < H; i++) {
			cin >> land[i];
		}

		int cnt = 0;
		for (int i = 0; i < H; i++) {
			for  (int j = 0; j < W; j++) {
				if (land[i][j] != '0') {
					cnt++;
					dfs(i, j, land[i][j]);
				}
			}
		}
		cout << cnt << endl;
	}

   return 0;
}



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

#define ld long double
#define ll long long
#define ALL(a)  (a).begin(),(a).end()
#define spa << " " <<
ll MOD = 1e9+7;
void chmin(long long &a, long long b) { if (a > b) a = b; }

bool compare_by_b(pair<ll, ll> a, pair<ll, ll> b) {
    if(a.second != b.second){
        return a.second < b.second;
    }else{
        return a.first < b.first;
    }
}

int main(){
  ll i , j;
  ll n;
  ll a, b;
  cin >> n;
  vector<pair<ll, ll>> pairs(n);
  for(i = 0; i < n; i++){
    cin >> a >> b;
    pairs[i] = make_pair(a, a + b);
  }
  sort(ALL(pairs), compare_by_b);
  reverse(ALL(pairs));
  ll result = 0;
  for(i = 0; i < n; i += 2){
    if(i < n - 1)
      result += pairs[i].first - (pairs[i+1].second - pairs[i+1].first);
    else
      result += pairs[i].first;
  }
  cout << result << endl;

  return 0;
}

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

const int H = 10;
const int W = 10;
int G[H][W];
int ans[H][W];

void put(int i, int j) {
  const static int di[5] = {0,1,0,-1,0};
  const static int dj[5] = {1,0,-1,0,0};
  for(int k = 0; k < 5; ++k) {
    int ni = i + di[k];
    int nj = j + dj[k];
    if(ni < 0 || ni >= H) continue;
    if(nj < 0 || nj >= W) continue;
    G[ni][nj] ^= 1;
  }
}

bool rec(int i, int j) {
  if(j == W) {
    ++i;
    j = 0;
  }

  if(i == H) {
    for(int j = 0; j < W; ++j) {
      if(G[H-1][j]) return false;
    }
    return true;
  }

  if(i == 0) {
    ans[i][j] = 0;
    if(rec(i, j+1)) return true;
    ans[i][j] = 1;
    put(i, j);
    if(rec(i, j+1)) return true;
    put(i, j);
  } else {
    if(G[i-1][j]) {
      ans[i][j] = 1;
      put(i, j);
      if(rec(i, j+1)) return true;
      put(i, j);
    } else {
      ans[i][j] = 0;
      if(rec(i, j+1)) return true;
    }
  }
  return false;
}

int main() {
  int n;
  cin >> n;
  while(n--) {
    for(int i = 0; i < H; ++i) {
      for(int j = 0; j < W; ++j) {
        cin >> G[i][j];
      }
    }
    rec(0, 0);
    for(int i = 0; i < H; ++i) {
      for(int j = 0; j < W; ++j) {
        if(j) cout << " ";
        cout << ans[i][j];
      }
      cout << endl;
    }
  }
  return 0;
}

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

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

int main() {
	string s;
	cin >> s;
	if (s[0] == s[1] || s[1] == s[2] || s[2] == s[3]) {
		cout << "Bad" << endl;
		return 0;
	}
	cout << "Good" << endl;
	return 0;
}

Measured memory_bytes: 764
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+200,mod=1e9+7;
vector<int> g[N];
int n;

ll sz[N],tmp=1,a[N];
ll qpow(ll a,ll b)
{
	ll ans=1;
	while(b){
		if(b&1)ans=(ans*a)%mod;
		a=a*a%mod;
		b>>=1;
	}
	return ans;
}
void dfs(int u,int fa)
{
	sz[u]=1;
	for(auto to:g[u])
	{
		if(to==fa)continue;
		dfs(to,u);
		sz[u]+=sz[to];
	}
	tmp=(tmp*sz[u])%mod;
}
void dfs2(int u,int fa)
{
	for(auto to:g[u])
	{
		if(to==fa)continue;
		a[to]=a[u]*qpow(sz[to],mod-2)%mod*(n-sz[to])%mod;
		dfs2(to,u);
	}
}
int main()
{
    scanf("%d",&n);
    ll lc=1;
    for(ll i=2;i<=n;i++)
    {
    	int a,b;
		scanf("%d%d",&a,&b);
    	g[a].push_back(b);
    	g[b].push_back(a);
    	lc=(lc*i)%mod;
	}
	dfs(1,-1);
	a[1]=tmp;
	dfs2(1,-1);
	for(int i=1;i<=n;i++)printf("%lld\n",lc*qpow(a[i],mod-2)%mod);
} 

Measured memory_bytes: 17012
#include <iostream>
#include <string>
using namespace std;
int main(){
  int n,count=1;
  string a;
  cin>>n;
  cin>>a;
  char j=a[0];
  for(int i=1;i<n;i++){
    if(j!=a[i]){
      count++;
      j=a[i];
    }
  }
  cout<<count<<endl;
  return 0;
}

Measured memory_bytes: 512
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <cmath>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
using P = pair<int, int>;
int mod = (int) 1e9 + 7;

int main(){
    
    int a, b;
    cin >> a >> b;
    int c = a * b;
    cout << c << "\n";
    
    return 0;
}



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

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define copy(from, to) copy(from.begin(), from.end(), back_inserter(to));
#define sort(a) sort(a.begin(), a.end())

typedef long long ll;
using namespace std;

template<class T>
void load(vector<T> &v, int n) {
  for (int i = 0; i < n; ++i) {
    T t;
    cin >> t;
    v.push_back(t);
  }
}

int main() {
  int a, p;
  cin >> a >> p;
  
  cout << (3 * a + p) / 2 << endl;
}

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

#define ms(s, n) memset(s, n, sizeof(s))
#define f(i, a, b) for (int i = (a); i <=(b); i++)
#define FORd(i, a, b) for (int i = (a) - 1; i >= (b); i--)
#define FORall(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
#define sz(a) int((a).size())
#define present(t, x) (t.find(x) != t.end())
#define all(a) (a).begin(), (a).end()
#define uni(a) (a).erase(unique(all(a)), (a).end())
#define pb push_back
#define pf push_front
#define mp make_pair
#define fi first
#define se second
#define prec(n) fixed<<setprecision(n)
#define bit(n, i) (((n) >> (i)) & 1)
#define bitcount(n) __builtin_popcountll(n)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pi;
typedef vector<ll> vi;
typedef vector<pi> vii;
const int MOD = (int) 1e9 + 7;
const int MOD2 = MOD + 2; //1007681537;
const int INF = (int) 1e9;
const ll LINF = (ll) 1e18;
const ld PI = acos((ld) - 1);
const ld EPS = 1e-9;
inline ll gcd(ll a, ll b) {ll r; while (b) {r = a % b; a = b; b = r;} return a;}
inline ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}
inline ll fpow(ll n, ll k, int p = MOD) {ll r = 1; for (; k; k >>= 1) {if (k & 1) r = r * n % p; n = n * n % p;} return r;}
template<class T> inline int chkmin(T& a, const T& val) {return val < a ? a = val, 1 : 0;}
template<class T> inline int chkmax(T& a, const T& val) {return a < val ? a = val, 1 : 0;}
inline ll isqrt(ll k) {ll r = sqrt(k) + 1; while (r * r > k) r--; return r;}
inline ll icbrt(ll k) {ll r = cbrt(k) + 1; while (r * r * r > k) r--; return r;}
inline void addmod(int& a, int val, int p = MOD) {if ((a = (a + val)) >= p) a -= p;}
inline void submod(int& a, int val, int p = MOD) {if ((a = (a - val)) < 0) a += p;}
inline int mult(int a, int b, int p = MOD) {return (ll) a * b % p;}
inline int inv(int a, int p = MOD) {return fpow(a, p - 2, p);}
inline int sign(ld x) {return x < -EPS ? -1 : x > +EPS;}
inline int sign(ld x, ld y) {return sign(x - y);}
int modulo(int a, int b) { return (a % b + b) % b; }
#define db(x) cerr << #x << " = " << (x) << " ";
#define endln cerr << "\n";

/*
class Compare
{
  public:
    bool operator()(pi a,pi b)
    {
      if(a.first<b.first || (a.first==b.first && a.second>b.second))
        return true;
      return false;
    }
};
*/

int main()
{
	IOS;
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	ll a;
	cin >> a;
	cout << a + a*a + a*a*a << endl;
	// read the stuff at the bottom
	return 0;
}
/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/





























Measured memory_bytes: 3644
from math import sqrt
q = int(input())

class Segment(): pass

def dot(a, b):
    return sum([i * j for i,j in zip(a, b)])

def sub(a, b):
    return [a[0] - b[0],a[1] - b[1]]

def cross(a, b):
    return  a[0] * b[1] - a[1] * b[0]

def norm(a):
    return sqrt(a[0] ** 2 + a[1] ** 2)

def ccw(a, b, c):
    x = sub(b, a)
    y = sub(c, a)
    if cross(x, y) > 0: return 1
    if cross(x, y) < 0: return -1
    if dot(x, y) < 0: return 2
    if norm(x) < norm(y): return -2
    return 0

def intersect(p1, p2, p3, p4):
    return ccw(p1, p2, p3) * ccw(p1, p2, p4) <= 0 and \
           ccw(p3, p4, p1) * ccw(p3, p4, p2) <= 0

def getDistLP(s, p):
    return abs(cross(sub(s.r, s.l), sub(p, s.l))) / norm(sub(s.r, s.l))

def getDistSP(s, p):
    if dot(sub(s.r, s.l),sub(p, s.l)) < 0: return norm(sub(p, s.l))
    if dot(sub(s.l, s.r),sub(p, s.r)) < 0: return norm(sub(p, s.r))
    return getDistLP(s, p)

def getDist(s1, s2):
    if intersect(s1.l, s1.r, s2.l, s2.r): return 0
    return min(getDistSP(s1, s2.l), 
               getDistSP(s1, s2.r),
               getDistSP(s2, s1.l),
               getDistSP(s2, s1.r))

for i in range(q):
    xp0, yp0, xp1, yp1, xp2, yp2, xp3, yp3  = map(int, input().split())
    s1 = Segment()
    s2 = Segment()
    s1.l = [xp0, yp0]
    s1.r = [xp1, yp1]
    s2.l = [xp2, yp2]
    s2.r = [xp3, yp3]
    print(getDist(s1, s2))

Measured memory_bytes: 8004
#include "bits/stdc++.h"
using namespace std;
#define MAX 200000
#define SENTINEL 2000000000
typedef long long ll;

ll L[MAX / 2 + 2], R[MAX / 2 + 2];
bool flg = true;

void merge(ll A[], int n, int left, int mid, int right) {
	int n1 = mid - left;
	int n2 = right - mid;

	for (int i = 0; i < n1; ++i) L[i] = A[left + i];
	for (int i = 0; i < n2; ++i) R[i] = A[mid + i];
	L[n1] = R[n2] = SENTINEL;
	int i = 0, j = 0;

	for (int k = left; k < right; ++k) {
    if(L[i] == R[j]) flg = false;
		if (L[i] <= R[j]) {
			A[k] = L[i++];
		}
		else {
			A[k] = R[j++];
		}
	}
}

void mergeSort(ll A[], int n, int left, int right) {
	if (left + 1 < right) {
		int mid = (left + right) / 2;
		mergeSort(A, n, left, mid);
		mergeSort(A, n, mid, right);
		merge(A, n, left, mid, right);
	}
}

int main() {
  int N; cin >> N;
  ll A[MAX];

  for(int i=0; i<N; ++i) cin >> A[i];

  mergeSort(A, N, 0, N);

  if(flg) cout << "YES" << endl;
  else cout << "NO" << endl;
}


Measured memory_bytes: 3328
#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;
using ll = long long;
using ld = long double;

#define fi first
#define se second
#define m_p make_pair
#define p_b push_back
#define e_b emplace_back
#define all(x) (x).begin(),(x).end()
#define uniq(x) ((x).erase(unique(all(x)),(x).end()))
#define sz(x) ((int)(x).size())

#define REP(i,m,n) for(int i=(int)(m);i<(int)(n);i++)
#define rep(i,n) REP(i,0,n)

string to_string(string s){
  return '"' + s + '"';
}
string to_string(const char *s){
  return to_string((string)s);
}
string to_string(bool b){
  return (b ? "true" : "false");
}
template<class A, class B>
string to_string(pair<A, B> p){
  return "(" + to_string(p.first) + ", " + to_string(p.second) + ")";
}
template<class A, class B, class C>
string to_string(tuple<A, B, C> p){
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")";
}
template<class A, class B, class C, class D>
string to_string(tuple<A, B, C, D> p){
  return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")";
}
template<class A>
string to_string(A v){
  bool first = true;
  string res = "{";
  for(const auto &x : v){
    if(!first){
      res += ", ";
    }
    first = false;
    res += to_string(x);
  }
  res += "}";
  return res;
}
void debug_out(){cerr << endl;}
template<class Head, class... Tail>
void debug_out(Head H, Tail... T){
  cerr << " " << to_string(H);
  debug_out(T...);
}
#ifdef LOCAL//compile with -DLOCAL
#define debug(...) cerr << "LINE" << __LINE__ << " [" << #__VA_ARGS__ << "]:", debug_out(__VA_ARGS__)
#else
#define debug(...) void(0)
#endif

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

int N;
ll C;

ll calc(vector<ll> &x, vector<ll> &v){
  ll ans = 0;
  vector<ll> sum_l(N+1,0);
  rep(i,N){
    sum_l.at(i+1) = sum_l.at(i) + v.at(i);
    chmax(ans, sum_l.at(i+1) - x.at(i));
  }

  vector<ll> point_lo(N+1,0);
  rep(i,N)  point_lo.at(i+1) = sum_l.at(i+1) - 2*x.at(i);
  ll sum_r = 0;
  ll point_r_mx = 0;
  for(int i = N; i >= 1; i--){
    chmax(ans, point_lo.at(i) + point_r_mx);
    sum_r += v.at(i-1);
    chmax(point_r_mx, sum_r - (C - x.at(i-1)));
  }
  return ans;
}

int main(){
  ios_base::sync_with_stdio(false);cin.tie(0);
  cin >> N >> C;
  vector<ll> x(N),v(N);
  rep(i,N)  cin >> x.at(i) >> v.at(i);

  ll ans = 0;
  chmax(ans, calc(x,v));
  reverse(all(x));
  reverse(all(v));
  rep(i,N)  x.at(i) = C - x.at(i);
  chmax(ans, calc(x,v));
  cout << ans << endl;

  return 0;
}

Measured memory_bytes: 6376
#include <bits/stdc++.h>
using namespace std;
int main(){
  while (1){
    int n, k, s;
    cin >> n >> k >> s;
    if (n == 0 && k == 0 && s == 0){
      break;
    }
    vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(k + 1, vector<int>(s + 1, 0)));
    dp[0][0][0] = 1;
    for (int i = 0; i < n; i++){
      for (int j = 0; j <= k; j++){
        for (int l = 0; l <= s; l++){
          dp[i + 1][j][l] += dp[i][j][l];
          if (l + i + 1 <= s && j < k){
            dp[i + 1][j + 1][l + i + 1] += dp[i][j][l];
          }
        }
      }
    }
    cout << dp[n][k][s] << endl;
  }
}


Measured memory_bytes: 3232
n,m,l = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for y in range(n)]
b = [[int(x) for x in input().split()] for y in range(m)]
c = [[0 for x in range(l)] for y in range(n)]

for i in range(n):
    for j in range(l):
        for k in range(m):
            c[i][j] += a[i][k] * b[k][j]
for i in range(n):
    print(" ".join(map(str,c[i])))

Measured memory_bytes: 8836
import java.io.{BufferedOutputStream, BufferedReader, InputStreamReader, PrintWriter}

object Main {
  def main(args: Array[String]): Unit = {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedOutputStream(System.out))
    val Array(a, b) = in.readLine().split("\\s+").map(_.toInt)

    out.println((a + b) % 24)

    out.flush()
  }
}


Measured memory_bytes: 25424
#include<stdio.h>  
   
int x[105][105],y[10000+50];  
   
int main ()  
{  
    int h,w;  
    while(scanf("%d %d",&h,&w)!=EOF)  
    {  
        int i,j,t,k=0;  
        scanf("%d",&t);  
        for(i=0;i<t;i++)  
            scanf("%d",&y[i]);  
        for(i=0;i<h;i++)  
        {  
            if(i%2==0)  
                for(j=0;j<w;j++)  
                {  
                    x[i][j]=k+1;  
                    y[k]--;  
                    if(y[k]==0)  
                        k++;  
                }  
            if(i%2==1)  
                for(j=w-1;j>=0;j--)  
                {  
                    x[i][j]=k+1;  
                    y[k]--;  
                    if(y[k]==0)  
                        k++;  
                }  
        }  
        for(i=0;i<h;i++)  
        {  
            for(j=0;j<w-1;j++)  
                printf("%d ",x[i][j]);  
            printf("%d\n",x[i][w-1]);  
        }  
    }  
} 

Measured memory_bytes: 256
#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations,permutations,accumulate # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
#import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
def readInts():
  return list(map(int,input().split()))
def I():
  return int(input())
dx = [-1,0,1,0]
dy = [0,-1,0,1]
h,w = readInts()
S = [list(input()) for _ in range(h)]
def bfs(y,x):
    dq = deque()
    dq.append((y,x))
    res = -1
    dist = [[-1] * w for _ in range(h)]
    dist[y][x] = 0
    while dq:
        y,x = dq.popleft()
        res = max(res,dist[y][x])
        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if not(0 <= ny < h and 0 <= nx < w):
                continue
            if S[ny][nx] == '#' or dist[ny][nx] != -1:
                continue
            dist[ny][nx] = dist[y][x] + 1
            dq.append((ny,nx))
    return res
ans = -1
for y in range(h):
    for x in range(w):
        if S[y][x] != '#':
            ans = max(ans,bfs(y,x))
print(ans)


Measured memory_bytes: 10416
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define H 12
#define W 6
typedef vector <string> VS;

const int dr[4] = { 0, 0, 1, -1 };
const int dc[4] = { 1, -1, 0, 0 };
VS field;

int calc( char c, int row, int col )
{
	int s = 0;
	for ( int i = 0; i < 4; i++ )
	{
		int nr = row + dr[i];
		int nc = col + dc[i];
		if ( nr < 0 || nr >= H || nc < 0 || nc >= W ) continue;
		if ( c == field[nr][nc] )
		{
			field[nr][nc] = '.';
			s += calc( c, nr, nc );
			field[nr][nc] = c;
		}
	}
	return 1 + s;
}

void remove( char c, int row, int col )
{
	for ( int i = 0; i < 4; i++ )
	{
		int nr = row + dr[i];
		int nc = col + dc[i];
		if ( nr < 0 || nr >= H || nc < 0 || nc >= W ) continue;
		if ( 'O' == field[nr][nc] ) field[nr][nc] = '.';
		if ( c == field[nr][nc] )
		{
			field[nr][nc] = '.';
			remove( c, nr, nc );
		}
	}
}

bool check()
{
	bool removed = false;
	for ( int i = 0; i < H; i++ )
	{
		for ( int j = 0; j < W; j++ )
		{
			if ( field[i][j] == 'O' || field[i][j] == '.' ) continue;
			char c = field[i][j];
			field[i][j] = '.';
			if ( calc( c, i, j ) >= 4 )
			{
				remove( c, i, j );
				removed = true;
			}
			else
				field[i][j] = c;
		}
	}
	return removed;
}

bool update()
{
	bool more = false;
	bool updated = true;
	while ( updated )
	{
		updated = false;
		for ( int i = 0; i + 1 < H; i++ )
		{
			for ( int j = 0; j < W; j++ )
			{
				if ( field[i][j] != '.' && field[i+1][j] == '.' )
				{
					swap( field[i][j], field[i+1][j] );
					updated = true;
					more = true;
				}
			}
		}
	}
	return more;
}

int main( void )
{
	int n;
	cin >> n;
	cin.clear();
	cin.ignore();

	for ( int lpc = 0; lpc < n; lpc++ )
	{
		field = VS( H );
		for ( int i = 0; i < H; i++ ) cin >> field[i];

		int answer = 0;
		do {
			if ( check() ) answer++;
		} while ( update() );

		cout << answer << endl;
	}

	return 0;
}

Measured memory_bytes: 0