akhauriyash/Code-Regression huggingface dataset:
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            String s = in.next();
            if (s.charAt(0) != 'A') {
                out.println("WA");
                return;
            }
            if (s.charAt(1) < 'a' || s.charAt(1) > 'z') {
                out.println("WA");
                return;
            }
            if (s.charAt(s.length() - 1) < 'a' || s.charAt(s.length() - 1) > 'z') {
                out.println("WA");
                return;
            }
            int cc = 0;
            for (int i = 2; i < s.length() - 1; i++) {
                if (s.charAt(i) == 'C')
                    cc++;
                if (s.charAt(1) < 'a' || s.charAt(1) > 'z') {
                    out.println("WA");
                    return;
                }
            }
            out.println(cc == 1 ? "AC" : "WA");

        }

    }

    static class FastScanner {
        private InputStream in;
        private byte[] buffer = new byte[1024];
        private int bufPointer;
        private int bufLength;

        public FastScanner(InputStream in) {
            this.in = in;
        }

        private int readByte() {
            if (bufPointer >= bufLength) {
                if (bufLength == -1)
                    throw new InputMismatchException();

                bufPointer = 0;
                try {
                    bufLength = in.read(buffer);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (bufLength <= 0)
                    return -1;
            }
            return buffer[bufPointer++];
        }

        private static boolean isPrintableChar(int c) {
            return c >= 33 && c <= 126;
        }

        public String next() {
            StringBuilder sb = new StringBuilder();

            int b = readByte();
            while (!isPrintableChar(b))
                b = readByte();

            while (isPrintableChar(b)) {
                sb.appendCodePoint(b);
                b = readByte();
            }

            return sb.toString();
        }

    }
}



Measured memory_bytes: 21460
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<inttypes.h>

typedef struct directed_edge {
  int32_t vertex;
  int32_t next;
} graph_edge;

typedef struct directedGraph {
  graph_edge *edge;
  int32_t *start;
  int32_t pointer;
  int32_t vertex_num;
  int32_t edge_max_size;
} graph;

graph* new_graph (const int vertex_num) {
  graph *g = (graph *) calloc (1, sizeof (graph));
  g->edge = (graph_edge *) calloc (1, sizeof (graph_edge));
  g->start = (int32_t *) calloc (vertex_num, sizeof (int32_t));
  g->pointer = 0;
  g->vertex_num = vertex_num;
  g->edge_max_size = 1;
  for (int32_t i = 0; i < vertex_num; ++i) {
    g->start[i] = -1;
  }
  return g;
}

void add_edge (graph *g, int32_t from, int32_t to) {
  if (g->pointer == g->edge_max_size) {
    g->edge_max_size *= 2;
    g->edge = (graph_edge *) realloc (g->edge, sizeof (graph_edge) * g->edge_max_size);
  }
  g->edge[g->pointer] = (graph_edge) {to, g->start[from]};
  g->start[from] = g->pointer++;
}

typedef int32_t i32;

void run (void) {
  i32 n, m;
  scanf ("%" SCNi32 "%" SCNi32, &n, &m);
  char *s = (char *) calloc (n + 1, sizeof (char));
  scanf ("%s", s);
  graph *g = new_graph (n);
  while (m--) {
    i32 a, b;
    scanf ("%" SCNi32 "%" SCNi32, &a, &b);
    a--;
    b--;
    add_edge (g, a, b);
    add_edge (g, b, a);
  }
  i32 *cnt = (i32 *) calloc (2 * n, sizeof (i32));
  for (i32 i = 0; i < n; ++i) {
    i32 d = s[i] == 'A' ? 0 : n;
    for (i32 p = g->start[i]; p != -1; p = g->edge[p].next) {
      i32 u = g->edge[p].vertex;
      cnt[u + d]++;
    }
  }
  i32 *q = (i32 *) calloc (n, sizeof (i32));
  uint8_t *used = (uint8_t *) calloc (n, sizeof (uint8_t));
  i32 front = 0;
  i32 last = 0;
  for (i32 i = 0; i < n; ++i) {
    if (cnt[i] == 0 || cnt[i + n] == 0) {
      q[last++] = i;
      used[i] = 1;
    }
  }
  while (front < last) {
    const i32 v = q[front++];
    const i32 d = s[v] == 'A' ? 0 : n;
    for (i32 p = g->start[v]; p != -1; p = g->edge[p].next) {
      i32 u = g->edge[p].vertex;
      cnt[u + d]--;
      if (!used[u] && cnt[u + d] == 0) {
	q[last++] = u;
	used[u] = 1;
      }
    }
  }
  puts (last < n ? "Yes" : "No");
}

int main (void) {
  run ();
  return 0;
}


Measured memory_bytes: 6656
#include <bits/stdc++.h>
#define REP(i, n) for(int i = 0; i < n; i++)
using namespace std;
using ll = long long;
const int INF = 1e9;
const ll LINF = 1e18;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  ll N;
  cin >> N;
  vector<ll> a(N);
  REP(i, N) cin >> a[i];
  vector<ll> R(N + 1);
  R[0] = 0;
  for(ll i = 0; i < N; i++) {
    R[i + 1] = R[i] + a[i];
  }
  ll ans = LLONG_MAX;
  for(ll i = 1; i < N; i++) {
    ans = min(ans, abs(R[i] * 2 - R[N]));
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 3456
#include<stdio.h>
int main(void){
  int a,b,c,d,sum=0;
  scanf("%d%d%d%d",&a,&b,&c,&d);
  if(a>b){
    sum+=b;
  }else{
    sum+=a;
  }
  if(c>d){
    sum+=d;
  }else{
    sum+=c;
  }
  printf("%d\n",sum);
  return(0);
}


Measured memory_bytes: 128
from operator import itemgetter
N = int(input())

rest_list = []
for i in range(N):
  town, score = input().split(' ')
  rest_list.append(('{}'.format(i),town,int(score)))

sort1 = sorted(rest_list,key=itemgetter(2),reverse=True)
sort2 = sorted(sort1,key=itemgetter(1))

for i in range(N):
  print('{}'.format(int(sort2[i][0])+1))

Measured memory_bytes: 3064
n, maxw = list(map(int, input().split()))

dp = [0 for _ in range(maxw+1)]
for i in range(n):
    v, c = list(map(int, input().split()))
    for j in range(maxw, -1, -1):
        if j>=c:
            dp[j] = max(dp[j], dp[j-c]+v)
        else:
            break
print(dp[-1])

Measured memory_bytes: 7984
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <algorithm>

using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep1(i, s, n) for (int i = (s); i <= (n); i++)
#define rrep(i, n) for (int i = (n) - 1; i >= 0; i--)
typedef long long ll;
typedef unsigned long long ull;

int L[2000];
int less_than[2001] = { 0 };

int main()
{
	int N;
	ll ans = 0;

	cin >> N;
	rep(i, N) cin >> L[i];

	sort(L, L + N);

	rep(i, N) {
		less_than[L[i]]++;
	}
	rep1(i, 1, 2000) {
		less_than[i] += less_than[i - 1];
	}

	rep1(i, 0, N - 2) {
		rep1(j, i + 1, N - 1) {
			ans += (ll)max(less_than[L[i] + L[j] - 1] - j - 1, 0);
		}
	}

	cout << ans << endl;

	return 0;
}


Measured memory_bytes: 256
#include"bits/stdc++.h"

using namespace std;

#define FastIO ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

#define nl "\n"
#define sp " "
#define int long long
#define PI 3.141592653589793
#define scanstr(s) cin>>ws; getline(cin,s);

void solve()
{
	int m,n;
	cin>>n>>m;
	int a[m],b[m];
	for(int i=0;i<m;i++)
	{
		cin>>a[i]>>b[i];
	}
	int mn=*max_element(a,a+m);
	int mx=*min_element(b,b+m);
	cout<<max(0LL,mx-mn+1)<<endl;
}

int32_t main()
{
	FastIO;
	solve();
	return 0;
}


Measured memory_bytes: 5172
#include<stdio.h>

int main(void){
int n,a,i,ii,y,s[2048];
scanf("%d",&n);
for(i=1;i<=n;i++){
    scanf("%d",&a);
    s[i] = a;
}
for(i=0;i<=9;i++){
    y=0;
    for(ii=1;ii<=n;ii++){ 
        if(s[ii]==i){
            y=1;
            break;
        }
    }
    if(y==0){
        printf("%d\n",i);
        return 0;
    }
}
for(i=10;i<=99;i++){
    y=0;
    for(ii=1;ii<=n-1;ii++){ 
        if(s[ii]==i/10 &&s[ii+1]==i%10){
            y=1;
            break;
        }
    }
    if(y==0){
        printf("%d\n",i);
        return 0;
    }
}
for(i=100;i<=999;i++){
    y=0;
    for(ii=1;ii<=n-2;ii++){ 
        if(s[ii]==i/100 &&s[ii+1]==(i/10)%10 &&s[ii+2]==i%10){
            y=1;
            break;
        }
    }
    if(y==0){
        printf("%d\n",i);
        return 0;
    }
}
return 0;
}

Measured memory_bytes: 2768
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int X = sc.nextInt();
		int answer=1;
		int num=1;
		int finNum=(int)Math.sqrt(X);
		for(int b =2 ; b <= 100 && b<=finNum ; b++) {//100^2まで
			for(int p=2; num<=X ;p++) {
				num=bekijyo(b,p);
				if(num>X) {
					num=bekijyo(b,p-1);
					break;
				}
			}
			answer=Math.max(num, answer);
		}
		System.out.println(answer);
	}
	public static int bekijyo(int b , int p) {
		if(p==0)return 0;
		int ret=b;
		for(int a=1 ; a<p ; a++) {
			ret=ret*b;
		}
		return(ret);
	}
}

Measured memory_bytes: 21972
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <numeric>
#include <queue>
#include <stack>
#include <map> 
#include <set>
#include <string>
#include <functional>
#include <list>
#include <random>
#include <time.h>
#include <iomanip>
#include <assert.h>
#include <numeric>
#define int long long
#define ll long long
#define double long double
#define mod 1000000007
#define MAXN (int)1e+5 * 2+1
#define LL_MAX 9223372036854775807	//ない環境用
#define LL_HALFMAX 9223372036854775807 / 2	//ない環境用
#define MIN -(9223372036854775807 / 2)
#define INF 9223372036854775807 / 2
#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()
#define REPS(i,x) for(int i=1;i<=(int)(x);i++)
#define RREP(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define RREPS(i,x) for(int i=((int)(x));i>0;i--)
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define mp make_pair


using namespace std;

std::mt19937 mt((int)time(0));

int dx[4] = { 0, 1, 0, -1 }; // x軸方向への変位
int dy[4] = { 1, 0, -1, 0 }; // y軸方向への変位

using Weight = int;
using Flow = int;
struct Edge {
	int src, dst;
	Weight weight;
	Flow cap;
	Edge() : src(0), dst(0), weight(0) {}
	Edge(int s, int d, Weight w) : src(s), dst(d), weight(w) {}
};
using Edges = std::vector<Edge>;
using Graph = std::vector<Edges>;
using Array = std::vector<Weight>;
using Matrix = std::vector<Array>;

void add_edge(Graph &g, int a, int b, Weight w = 1) {
	g[a].emplace_back(a, b, w);
	g[b].emplace_back(b, a, w);
}
void add_arc(Graph &g, int a, int b, Weight w = 1) { g[a].emplace_back(a, b, w); }

int w[100001], b[100001];

signed main() {

	int N, P;
	cin >> N >> P;

	int score = 0;

	rep(i, N) {
		cin >> w[i] >> b[i];
		score -= b[i]*P;
	}

	vector<int> scores;

	rep(i, N) {
		int x = (100 - P)*w[i] + P * b[i];
		scores.push_back(x);
	}
	sort(scores.begin(), scores.end());
	reverse(scores.begin(), scores.end());
	
	int ans = 0, i = 0;
	while (score < 0) {
		score += scores[i];
		i++;
		ans++;
	}
	cout << ans << "\n";


	return 0;
}

Measured memory_bytes: 2936
#include <bits/stdc++.h>
#define sanyes ios_base::sync_with_stdio(0), cout.tie(0); cin.tie(0);
#define llong long long int
#define pb push_back
#define bpc __builtin_popcount
#define f first
#define s second

const llong mxn = 1e5 + 7;
const llong mod = 1e9 + 7;
const llong inf = 1e18 + 9;

using namespace std;

llong n, a[mxn], dp[mxn], p1, p2, cnt = 1;

int main(){
    cin >> n;
    for (int i = 1; i <= n; i ++){
        cin >> a[i];
    }//if(a[2] > a[1]) p1 = 1;
    //if(a[2] < a[1]) p2 = 1;
    for (int i = 2; i <= n; i ++){
        if(a[i - 1] < a[i]){
            p1 = 1;
        }if(a[i - 1] > a[i]){
            p2 = 1;
        }if(p1 == 1 && p2 == 1){
            cnt ++;
            p1 = p2 = 0;
        }
    }cout << cnt;
    return 0;
}


Measured memory_bytes: 1024
//Fibonacci Number
#include <iostream>

using namespace std;

const int NIL = -1;

int fibonacci(int fib[], int n) {
    if(fib[n] != NIL) return fib[n];
    fib[n] = fibonacci(fib, n - 1) + fibonacci(fib, n - 2);
    return fib[n];
}

int main() {
    int n;
    cin >> n;
    int fib[n + 1];
    for(int i = 0; i < n + 1; i++) {
        fib[i] = NIL;
    }
    fib[0] = 1;
    if(n > 0) fib[1] = 1;

    cout << fibonacci(fib, n) << endl;
}


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

#define SIZE_OF_ARRAY(array) sizeof(array)/sizeof(array[0])

int main() {
    long long N, M;
    cin >> N >> M;
    long long A[N];
    long long sum = 0;
    for(long long i = 0; i < N; i++){
        cin >> A[i];
        sum += A[i];
    }
    long long m = 0;
    for(long long i = 0; i < N; i++){
        if( A[i] * 4 * M >= sum){
            m++;
        }
    }
    if(m >= M){
        cout << "Yes";
    } else {
        cout << "No";
    }

}

Measured memory_bytes: 256
# coding: utf-8

II = lambda: int(input())
MI = lambda: map(int, input().split())


def sumcnt(values):
    sc = [0] * (50 * 50 + 1)
    sc[0] = 1
    max_sc = 0
    for v in values:
        for i in range(max_sc, -1, -1):
            sc[i + v] += sc[i]
        max_sc += v
    return sc, max_sc


def main():
    N, A = MI()
    ds = [x-A for x in MI()]

    count0 = 0
    dp, dm = [], []
    for d in ds:
        if d == 0: count0 += 1
        elif d > 0: dp.append(d)
        else: dm.append(-d)
    dp.sort()
    dm.sort()

    scp, scpmax = sumcnt(dp)
    scm, scmmax = sumcnt(dm)

    ans = 0
    for i in range(1, min(scpmax, scmmax) + 1):
        ans += scp[i] * scm[i]
    ans = ans * (2**count0) + 2**count0 - 1
    return ans


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


Measured memory_bytes: 3064
import std.algorithm, std.container, std.conv, std.math, std.range, std.typecons, std.stdio, std.string;

auto rdsp(){return readln.splitter;}
void pick(R,T)(ref R r,ref T t){t=r.front.to!T;r.popFront;}
void readV(T...)(ref T t){auto r=rdsp;foreach(ref v;t)pick(r,v);}
void readA(T)(size_t n,ref T[]t){t=new T[](n);auto r=rdsp;foreach(ref v;t)pick(r,v);}

void main()
{
  int n; readV(n);
  int[] a; readA(n, a);

  auto cl = new long[](n), cr = new long[](n);
  cl[0] = a[0];
  foreach (i; 1..n) cl[i] = cl[i-1]+a[i];
  cr[0] = a[$-1];
  foreach (i; 1..n) cr[i] = cr[i-1]+a[$-1-i];

  auto r = 10L^^18;
  foreach (i; 2..n-1) {
    auto d1 = divide(cl[0..i]);
    auto d2 = divide(cr[0..n-i]);
    r = min(r, max(d1[1], d2[1])-min(d1[0], d2[0]));
  }

  writeln(r);
}

auto divide(long[] c)
{
  auto t = c[$-1], cs = c.assumeSorted;
  if (t%2 == 0 && cs.contains(t/2))
    return [t/2, t/2];
  auto a = cs.lowerBound(t/2+1), b = cs.upperBound(t/2);
  if (a.empty)
    return [t-c[0], c[0]];
  auto a1 = a.back, a2 = t-a1, b2 = b.front, b1 = t-b2;
  if (a2-a1 < b2-b1)
    return [a1, a2];
  else
    return [b1, b2];
}


Measured memory_bytes: 8624
import math

def is_prime(n):
    if n == 1: return False

    for k in range(2, int(math.sqrt(n)) + 1):
        if n % k == 0:
            return False

    return True
x=int(input())
for i in range(x,x+10**5):
  if is_prime(i)==True:
    break
print(i)
  

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

using namespace std;

int main(void){
  int N;
  cin >> N;
  map<int, long long> f;
  for(int i = 1; i <= N; i++){
    int ii = i;
    for(int j = 2; ii > 1; j++){
      while(ii % j == 0){
        ii /= j;
        f[j] += 1;
      }
    }
  }
  long long ans = 1;
  for(auto ff : f){
    ans *= ff.second + 1;
    ans %= 1000000007;
  }
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#define ALL(X) X.begin(), X.end()
#define SZ(A) int((A).size())
#define RALL(X) X.rbegin(), X.rend()
#define FOR(B) for (size_t i = 0; i < B; i++)
#define FOR2(B) for (size_t j = 0; j < B; j++)
#define FORE(B) for (size_t i = 1; i <= B-1; i++)
#define FORC(A, B) for (size_t i = A; i < B; i++)
#define PRINT(X) cout << X << endl
#define PRINTALL(E, X) { FOR(X) {cout << E[i] << endl; } }
#define PRINTSIDE(E, X) { FOR(X) {cout << E[i] << " ";} }
#define READALLI(V, N) FOR(N) {int x; cin >> x; V.push_back(x); }
#define READALL(V, N) FOR(N) {LL x; cin >> x; V.push_back(x); }
#define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define MAXN 100000
#define SQRSIZE  317
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector<VI> VII;
typedef vector<LL>VL;
typedef vector<PII> VPII;
typedef map<int, int> MII;
typedef map<char, int>MCI;
typedef map<string, int> MSI;
typedef set<int> SI;
const int INF = (1 << 30);


int main () {
	int n = 0;
	cin >> n;
	set<string> words;
	bool first = true, ans = true;
	char lastChar = ' ';
	FOR(n){
		string s = "";
		cin >> s;
		if(!first){
			if(s[0] != lastChar){
				ans = false;
			}
		}
		words.insert(s);
		lastChar = s[s.size() - 1];
		first = false;
	}
	if(ans && words.size() == n){
		cout << "Yes\n";
	}else{
		cout << "No\n";
	}
	return 0;
}

Measured memory_bytes: 256
N,M,Q = map(int,input().split())
A = [[0 for _ in range(N+1)] for _ in range(N+1)]
for _ in range(M):
    L,R = map(int,input().split())
    A[L][R] += 1
dp = [[0 for _ in range(N+1)] for _ in range(N+1)]
dp[N][N] = A[N][N]
for i in range(N-1,0,-1):
    for j in range(i,N+1):
        dp[i][j] = A[i][j]
        if j>i:
            dp[i][j] += dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]
for _ in range(Q):
    p,q = map(int,input().split())
    print(dp[p][q])

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

int N;
double dp[310][310][310];

double rec(int a,int b,int c){
  if(dp[a][b][c]>0) return dp[a][b][c];
  if(a==0 && b==0 && c==0) return 0;
  double ret = 0;
  if(a>0) ret += rec(a-1,b,c) * a;
  if(b>0) ret += rec(a+1,b-1,c) * b;
  if(c>0) ret += rec(a,b+1,c-1) * c;
  ret += N;
  ret /= (a+b+c);
  return dp[a][b][c] = ret;
}

int main(){
  cin >> N;
  int a=0,b=0,c=0;
  for(int i=0;i<N;++i){
    int n;
    cin >> n;
    if(n==1) a++;
    else if(n==2) b++;
    else c++;
  }
  
  cout << fixed << setprecision(10) << rec(a,b,c) << endl;
  return 0;
}

Measured memory_bytes: 225536
#include <bits/stdc++.h>
#define REP(i,a,b) for(int i=(a);i<(b);i++)
#define RREP(i,a,b) for(int i=(a);i>=(b);i--)
typedef long long ll; typedef long double ld;
using namespace std;
const int INF=1e9, MOD=1e9+7;
int h,w,li[55][55]={};
string s[51];

int main(){
	cin >> h >> w;
	REP(i,0,h) cin >> s[i];
	
	REP(i,0,h){
		REP(j,0,w){
			if(s[i][j]=='#') li[i][j]=-1;
		}
	}
	
	REP(i,0,h){
		REP(j,0,w){
			if(s[i][j]=='#'){
				if(s[i][j+1]=='.') 							li[i][j+1]+=1;
				if(j-1>=0 and s[i][j-1]=='.') 				li[i][j-1]+=1;
				if(s[i+1][j]=='.') 							li[i+1][j]+=1;
				if(i-1>=0 and s[i-1][j]=='.') 				li[i-1][j]+=1;
				if(i-1>=0 and j-1>=0 and s[i-1][j-1]=='.') 	li[i-1][j-1]+=1;
				if(i-1>=0 and s[i-1][j+1]=='.') 			li[i-1][j+1]+=1;
				if(j-1>=0 and s[i+1][j-1]=='.') 			li[i+1][j-1]+=1;
				if(s[i+1][j+1]=='.') 						li[i+1][j+1]+=1;
			}
		}
	}
	
	REP(i,0,h){
		REP(j,0,w){
			if(li[i][j]==-1) cout << '#';
			else cout << li[i][j];
		}
		cout << endl;
	}
	
	return 0;
}


Measured memory_bytes: 256
from bisect import  bisect

def convert(number) :
    if number == 0 :
        out = "0"
    else :
        out = ""
    while number > 0 :
        surplus = (number % 4)
        out = str(surplus) + out
        number //= 4
    return out

def seven_five_three(string) :
    string = string.replace("3","7").replace("2","5").replace("1","3")
    return string

L = []
for i in range(3*10**5) :
    l = convert(i)
    l = seven_five_three(l)
    if (("0" in l) or ("3" not in l) or ("5" not in l) or ("7" not in l)) :
        continue
    l = int(l)
    L.append(l)

N = int(input())
ans = bisect(L,N)
print(ans)


Measured memory_bytes: 4184
from math import *

n = int(input())
a = list(map(int, input().split()))
DP = [0 for i in range(n)]

DP[0] = 0
DP[1] = abs(a[1] - a[0])

for i in range(2, n):
   DP[i] = min(DP[i-1] + abs(a[i] - a[i-1]), DP[i-2] + abs(a[i] - a[i-2]))

print(DP[n-1])


Measured memory_bytes: 14480
use std::vec::Vec;

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace().map(|e| e.parse().ok().unwrap()).collect()
}

fn main() {
    let (h, w) = {
        let v: Vec<usize> = read_vec();
        (v[0], v[1])
    };

    let mut s = Vec::new();
    for _ in 0..h {
        let v: Vec<char> = read::<String>().chars().collect();
        s.push(v);
    }

    for (i, line) in s.iter().enumerate() {
        for (j, &c) in line.iter().enumerate() {
            if c == '#' && !check((i, j), &s) {
                println!("No");
                return
            }
        }
    }

    //println!("{:?}", s);
    println!("Yes");
}

fn adj_position(pos: (usize, usize), h: usize, w: usize) -> Vec<(usize, usize)> {
    let (x, y) = pos;

    let mut res = Vec::new();

    // x方向
    if x > 0 { 
        res.push((x-1, y)); 
    }

    if x < w-1 {
        res.push((x+1, y)); 
    }

    // y方向
    if y > 0 {
        res.push((x, y-1));
    }

    if y < h-1 {
        res.push((x, y+1));
    }

    res
}

fn check(pos: (usize, usize), board: &Vec<Vec<char>>) -> bool {
    let (x, y) = pos;
    let adj_list = adj_position(pos, board.len(), board[0].len());

    for (i, j) in adj_list {
        if board[i][j] == '#' {
            return true;
        }
    }

    false
}

Measured memory_bytes: 4352
from itertools import combinations_with_replacement
from math import gcd
K = int(input())
memo = {}
ans = 0
for a,b,c in combinations_with_replacement(range(1,K+1),3):
  v = gcd(a, gcd(b,c))
  n = len(set([a,b,c]))
  ans += v if n==1 else (3*v if n==2 else 6*v)
print(ans)

Measured memory_bytes: 9204
N = int(input())
X = [int(i) for i in input().split()]

# X = sorted(X)
# X_undupe = list(set(X))
stamina = []
for i in range(1, 100):
    s = 0
    for ii in X:
        s = s + ((ii - i) ** 2)
    stamina.append(s)

print(min(stamina))


Measured memory_bytes: 2940
(defmacro defsolver (name vars &body body)
  `(defun ,name ()
     (let (,@(mapcar #'list
		    vars
		    (mapcar (constantly '(read))
			    vars)))
       ,@body)))

(defsolver prob-b (h w)
  (let ((bar (format nil "~a" (coerce (loop repeat (+ 2 w) collect #\#) 'string))))
    (format t "~a~%" bar)
    (dotimes (i h)
      (format t "#~a#~%" (read-line)))
    (format t "~a~%" bar)))

(prob-b)

Measured memory_bytes: 16996
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=3000;
const int maxm=4000;
const int mod=1e9+7;
int n,m,tot;
int l[maxn+8],r[maxn+8],fac[maxn+8],fact[maxn+8],tmp[maxm+8];
int f[maxm+8][maxm+8];
char S[maxn+8];
 
int read()
{
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
    return x*f;
}
 
int power(int a,int k)
{
    int sum=1;
    for (;k;k>>=1,a=1ll*a*a%mod)
	if (k&1)
	    sum=1ll*sum*a%mod;
    return sum;
}
 
int C(int n,int m){if (n<m) return 0;return 1ll*fac[n]*fact[m]%mod*fact[n-m]%mod;}
 
int main()
{
    n=read(),m=read();
    scanf("%s",S+1);
    for (int i=1;i<=m;i++)
	{
	    int x=read(),y=read();
	    if (r[tot]>=y) continue;
	    if (l[tot]==x&&r[tot]<y) tot--;
	    l[++tot]=x,r[tot]=y;
	}
    l[++tot]=n,r[tot]=n;
    fac[0]=fact[0]=1;
    for (int i=1;i<=n;i++) tmp[i]=tmp[i-1]+(S[i]=='1');
    for (int i=1;i<=n;i++) fac[i]=1ll*fac[i-1]*i%mod;
    fact[n]=power(fac[n],mod-2);
    for (int i=n-1;i;i--) fact[i]=1ll*fact[i+1]*(i+1)%mod;
    f[0][0]=1;
    for (int i=1;i<tot;i++)
	{
	    //printf("Time:%d\n",i);
	    if (l[i+1]>r[i])
		{
		    for (int j=0;j<=n;j++)
			f[i][0]=(f[i][0]+1ll*f[i-1][j]*C(r[i]-l[i]+1,j+tmp[r[i]]-tmp[max(l[i]-1,r[i-1])])%mod)%mod;
		    continue;
		}
	    for (int j=0;j<=r[i]-l[i+1]+1;j++)
		    for (int k=0;k<=l[i+1]-l[i]+j-tmp[r[i]]+tmp[max(l[i]-1,r[i-1])];k++)
			{
				if (!f[i-1][k]) continue;
			    //printf("update:%d %d\n",j,k);
			    f[i][j]=(f[i][j]+1ll*f[i-1][k]*C(l[i+1]-l[i],k-j+tmp[r[i]]-tmp[max(l[i]-1,r[i-1])])%mod)%mod;
			}
	}
    //for (int i=1;i<tot;i++,puts(""))
    // 	for (int j=0;j<=n;j++)
    //	    	    printf("%d ",f[i][j]);
    int ans=(f[tot-1][0]+f[tot-1][1])%mod;
       printf("%d\n",ans);
    return 0;
}


Measured memory_bytes: 19200
import java.util.Scanner;

public class Main {
	static Scanner sc = new Scanner(System.in);
	static String S = sc.nextLine();
	static String target = "keyence";
	public static void main(String[] args) {
		if (S.startsWith(target) || S.endsWith(target)
				|| S.matches("k.*eyence")
				|| S.matches("ke.*yence")
				|| S.matches("key.*ence")
				|| S.matches("keye.*nce")
				|| S.matches("keyen.*ce")
				|| S.matches("keyenc.*e")
				) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}
}

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

int main()
{
#ifdef WIN32
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    int h, w, m;
    cin >> h >> w >> m;
    int x, y;
    int row[h + 1], col[w + 1];
    memset(row, 0, sizeof(row));
    memset(col, 0, sizeof(col));
    set<pair<int, int>> s;
    for (int i = 1; i <= m; i++)
    {
        cin >> x >> y;
        s.insert({x, y});
        row[x]++;
        col[y]++;
    }
    x = 1;
    y = 1;
    for (int i = 1; i <= h; i++)
    {
        if (row[i] > row[x])
            x = i;
    }
    for (int i = 1; i <= w; i++)
    {
        if (col[i] > col[y])
            y = i;
    }
    int ans = 0;
    for (int i = 1; i <= w; i++)
    {
        if (s.find({x, i}) != s.end())
        {
            ans = max(ans, row[x] + col[i] - 1);
        }
        else
        {
            ans = max(ans, row[x] + col[i]);
        }
    }
    for (int i = 1; i <= h; i++)
    {
        if (s.find({i, y}) != s.end())
        {
            ans = max(ans, row[i] + col[y] - 1);
        }
        else
        {
            ans = max(ans, row[i] + col[y]);
        }
    }
    cout << ans << "\n";
    return 0;
}

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

int main(){
  int n,k;

  while(cin >> n >> k ,n | k){
    int sum = 0;
    int array[n];

    for(int i = 0 ; i < n ; i++){
      cin >> array[i];
    }
    for(int i = 0 ; i < k ; i++){
      sum += array[i];
    }

    int res = sum;
    for(int i = k ; i < n ; i++){
      sum += array[i];
      sum -= array[i-k];
      res = max(res,sum);
    }
    cout << res << endl;
  }

  return 0;
}

Measured memory_bytes: 1548
S = input()
Q = int(input())
T1 = 0
S_left = ''
S_right = ''
for _ in range(Q):
  a = list(map(str,input().split()))
  if a[0] == '1':
    T1 += 1
  elif a[0] == '2':
    if ((a[1]=='1')and(T1%2==0)) or ((a[1]=='2')and(T1%2!=0)):
      S_left = a[2]+S_left
    else:
      S_right = S_right+a[2]
S = S_left+S+S_right
if T1 % 2 == 0:
  print(S)
else:
  print(S[::-1])

Measured memory_bytes: 4572
using System;

class Modulo
{
    private const int MOD = 998244353;
    private readonly int[] m_facs;
    public int Mul(int a, int b) => (int)(Math.BigMul(a, b) % MOD);
    public Modulo(int n)
    {
        m_facs = new int[n + 1];
        m_facs[0] = 1;
        for (int i = 1; i <= n; ++i)
            m_facs[i] = Mul(m_facs[i - 1], i);
    }
    public int Fac(int n) => m_facs[n];
    public int Pow(int a, int m)
    {
        switch (m)
        {
            case 0:
                return 1;
            case 1:
                return a;
            default:
                int p1 = Pow(a, m / 2);
                int p2 = Mul(p1, p1);
                return ((m % 2) == 0) ? p2 : Mul(p2, a);
        }
    }
    public int Div(int a, int b) => Mul(a, Pow(b, MOD - 2));
    public int Ncr(int n, int r)
    {
        if (n < r) return 0;
        if (n == r) return 1;
        int res = Fac(n);
        res = Div(res, Fac(r));
        res = Div(res, Fac(n - r));
        return res;
    }
}


public class Hello
{
    public static int MOD = 998244353;
    public static void Main()
    {
        string[] line = Console.ReadLine().Trim().Split(' ');
        var n = int.Parse(line[0]);
        var m = int.Parse(line[1]);
        var k = int.Parse(line[2]);
        getAns(n, m, k);

    }
    static long calc (int n, int m, int k, Modulo md)
    {
        long a1 = md.Pow(m - 1, n - k - 1);
        a1 = (a1 * m) % MOD;
        long a2 = md.Ncr(n - 1, k);
        a1 = (a1 * a2) % MOD;
        return a1;
    }
    static void getAns(int n, int m, int k)
    {
        var md = new Modulo(n);
        var ans = 0L;
        for (int i = 0; i <= k; i++)
        {
            ans += calc(n, m, i ,md);
            ans %= MOD;
        }
        Console.WriteLine(ans);
    }
}



Measured memory_bytes: 28304
#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    let s = read::<String>().chars().collect::<Vec<_>>();
    let mut count = vec![0; 3];
    count[0] = s.iter().filter(|&&x| x == 'a').count();
    count[1] = s.iter().filter(|&&x| x == 'b').count();
    count[2] = s.iter().filter(|&&x| x == 'c').count();
    count.sort();

    if count[2] - count[0] <= 1 {
        println!("YES");
    } else {
        println!("NO");
    }
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}


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

typedef long long ll;
#define re(n) cin >> n
#define all(a) a.begin(),a.end()
#define fast std::ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define te(t) ll t; re(t); while(t--)

int main(){
	ll n;
	re(n);
	ll steps = LLONG_MAX;
	ll i;
	ll x = sqrt(n);
	if(sqrt(n)!=(float)sqrt(n)){
		x++;
	}
	for(i=1;i<=x;i++){
		if(n%i==0){
			steps = min(steps, (n/i)+i);
		}
	}
	cout << steps-2 << endl;
	return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;

int line[105][105];
int girl[105];
int used[105];
int n;
struct student{
    int x;
    int y;
};

bool _find(int x){
	int i,j;
	for (j=1;j<=n;j++){    //扫描每个妹子
		if (line[x][j]==true && used[j]==false)
		//如果有暧昧并且还没有标记过(这里标记的意思是这次查找曾试图改变过该妹子的归属问题，但是没有成功，所以就不用瞎费工夫了）
		{
			used[j]=1;
			if (girl[j]==0 || _find(girl[j])) {
				//名花无主或者能腾出个位置来，这里使用递归
				girl[j]=x;
				return true;
			}
		}
	}
	return false;
}

int main(){
    int a,b;
    cin>>n;
    student ans[105];
    student res[105];
    for (int i = 1; i <= n;i ++){
        cin>>a>>b;
        ans[i].x = a;
        ans[i].y = b;
    }
    for (int i = 1;i <= n; i++){
        cin>>a>>b;
        res[i].x = a;
        res[i].y = b;
    }
    for (int i = 1; i <= n; i++){
        for (int j = 1; j <= n; j++){
            if (ans[i].x<res[j].x&&ans[i].y<res[j].y){
                line[i][j] = 1;
            }
        }
    }
    int result = 0;
    for (int i = 1; i <= n;i++){
        memset(used,0,sizeof(used));
        if (_find(i)){
            result++;
        }
    }
    cout<<result<<endl;
}


Measured memory_bytes: 256
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(unused_imports)]

use std::str::FromStr;
use std::io::*;
use std::collections::*;
use std::cmp::*;

struct Scanner<I: Iterator<Item = char>> {
    iter: std::iter::Peekable<I>,
}

macro_rules! exit {
    () => {{
        exit!(0)
    }};
    ($code:expr) => {{
        if cfg!(local) {
            writeln!(std::io::stderr(), "===== Terminated =====")
                .expect("failed printing to stderr");
        }
        std::process::exit($code);
    }}
}

impl<I: Iterator<Item = char>> Scanner<I> {
    pub fn new(iter: I) -> Scanner<I> {
        Scanner {
            iter: iter.peekable(),
        }
    }

    pub fn safe_get_token(&mut self) -> Option<String> {
        let token = self.iter
            .by_ref()
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        if token.is_empty() {
            None
        } else {
            Some(token)
        }
    }

    pub fn token(&mut self) -> String {
        self.safe_get_token().unwrap_or_else(|| exit!())
    }

    pub fn get<T: FromStr>(&mut self) -> T {
        self.token().parse::<T>().unwrap_or_else(|_| exit!())
    }

    pub fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
        (0..len).map(|_| self.get()).collect()
    }

    pub fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
        (0..row).map(|_| self.vec(col)).collect()
    }

    pub fn char(&mut self) -> char {
        self.iter.next().unwrap_or_else(|| exit!())
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.get::<String>().chars().collect()
    }

    pub fn line(&mut self) -> String {
        if self.peek().is_some() {
            self.iter
                .by_ref()
                .take_while(|&c| !(c == '\n' || c == '\r'))
                .collect::<String>()
        } else {
            exit!();
        }
    }

    pub fn peek(&mut self) -> Option<&char> {
        self.iter.peek()
    }
}

trait Joinable {
    fn join(self, sep: &str) -> String;
}

impl<U: ToString, T: Iterator<Item = U>> Joinable for T {
    fn join(self, sep: &str) -> String {
        self.map(|x| x.to_string()).collect::<Vec<_>>().join(sep)
    }
}
fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin.bytes().map(|c| c.unwrap() as char));
    let N: usize = sc.get();
    let M: usize = sc.get();
    let A: Vec<usize> = sc.vec(N);
    let mut tot = 0;
    for i in 0..N {
        tot += A[i];
    }
    let mut cnt = 0;
    for i in 0..N {
        if A[i] * 4 * M >= tot {
            cnt += 1;
        }
    }
    if cnt >= M {
        println!("Yes");
    } else {
        println!("No");
    }
}


Measured memory_bytes: 4352
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10000000)
INF = 1<<32


def solve(A: "List[int]"):
    if sum(A) >= 22:
        print('bust')

    else:
        print('win')

        
    return




def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = [int(next(tokens)) for _ in range(3)]  # type: "List[int]"
    solve(A)

if __name__ == '__main__':
    main()


Measured memory_bytes: 3060
N = int(input())
H = list(map(int, input().split()))

ans = 0
for i in range(len(H)):
  chkflg = True
  if i >= 1:
    for j in range(i): 
      if H[j] > H[i]:
        chkflg = False
        break

  if chkflg: ans += 1

print(ans)   



Measured memory_bytes: 3060
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int q = sc.nextInt();

        Node nodes[] = new Node[n];
        for (int i=0; i<n; i++) nodes[i] = new Node();
        for (int i=0; i<n-1; i++){
            int a = sc.nextInt()-1;
            int b = sc.nextInt()-1;
            nodes[a].neighbors.add(nodes[b]);
            nodes[b].neighbors.add(nodes[a]);
        }

        for (int i=0; i<q; i++){
            int p = sc.nextInt()-1;
            nodes[p].offset += sc.nextInt();
        }

        dfs(null, nodes[0], 0);
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<n; i++){
            sb.append(nodes[i].counter).append(" ");
        }
        System.out.println(sb.toString());


    }

    private static void dfs(Node parent, Node node, int sum){
        sum += node.offset;
        node.counter = sum;
        for (Node n: node.neighbors){
            if (n != parent){
                dfs(node, n, sum);
            }
        }
    }


    private static class Node{
        private List<Node> neighbors = new ArrayList<>();
        private int offset;
        private int counter;
    }
}

Measured memory_bytes: 208512
// 問題の URL を書いておく
// 

#include <algorithm>
#include <array>
#include <bitset>
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <vector>

using namespace std;

//#define ENABLE_PRINT

#if defined(ENABLE_PRINT)

#define Print(v) \
do {\
    cout << #v << ": " << v << endl; \
}while(0)

#define PrintVec(v) \
do {\
    for(int __i = 0; __i < v.size(); ++__i) \
    { \
        cout << #v << "[" << __i << "]: " << v[__i] << endl; \
    }\
}while(0)

#else

#define Print(v) ((void)0)
#define PrintVec(v) ((void)0)

#endif

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

using ll = int64_t;

int main(int, const char**)
{
    int n;
    cin >> n;
    map<ll, ll> c0, c1;
    set<ll> vs;
    rep(i, n)
    {
        auto num = i + 1;
        ll a;
        cin >> a;
        auto v0 = num + a;
        if(c0.find(v0) == c0.end())
        {
            c0[v0] = 0;
        }
        c0[v0]++;
        vs.insert(v0);

        auto v1 = num - a;
        if(c1.find(v1) == c1.end())
        {
            c1[v1] = 0;
        }
        c1[v1]++;
        vs.insert(v1);
    }

    ll ans = 0;
    for(auto v : vs)
    {
        ans += c0[v] * c1[v];
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 66116
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <climits>
#include <map>
typedef long long ll;
using namespace std;

typedef pair<int,int> p;

int main()
{
  // input & declare
  int n,k;
  cin >> n >> k;
  std::map<int, int> map;
  int tmp;
  for(int i = 0; i < n; i++)
  {
    cin >> tmp;
    map[tmp]++;
  }

  // process
  std::vector<int> v;
  for (auto a : map) {
    v.push_back(a.second);
  }
  sort(v.begin(),v.end());
  int result = 0;
  for(int i = 0; i < (int)v.size() - k; i++)
  {
    result += v[i];
  }

  // output
  std::cout << result << '\n';
}


Measured memory_bytes: 10748
#include<bits/stdc++.h>
using namespace std;
int gcd(int x,int y)
{
  while(y!=0)
  {
  	int tmp=x;
  	x=y;
  	y=tmp%y;
  }
return x;
}
int main()
{
int n,x;
cin>>n>>x;
int g=0;
  for(int i=0;i<n;i++)
  {
  	int y;
  	cin>>y;
  	g=gcd(g,abs(y-x));
  }
cout<<g<<endl;
return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
#define int long long
#define rep(i,n) for(int i=0;i<n;++i)
#define all(a) a.begin(),a.end()
#define P pair<long long,long long>
#define double long double
using namespace std;
signed main(){
  string a;
  int b=0;
  cin>>a;
  if(a.at(0)=='A'&&islower(a.at(1))&&islower(a.at(a.size()-1))){
    for(int i=2;i<a.size()-1;i++){
      if(isupper(a.at(i))&&a.at(i)!='C'){
    cout<<"WA";
        break;
      }
  if(a.at(i)=='C')
    b++;
  if(b==2){
    cout<<"WA";
  break;
  }
    }
  if(b==0)
    cout<<"WA";
    else if(b!=2)
      cout<<"AC";
    }
  else
    cout<<"WA";
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
int main()
{
  int A;
  string op;
  int B;
  cin >> A >> op >> B;
  if(op == "+")
  {
    cout << A + B << endl;
  }
  else if(op == "-")
  {
    cout << A - B << endl;
  }
}

Measured memory_bytes: 3624
n = int(input())
def dfs(s):
  if len(s) == n:
    print(s)
  else:
    max_list = []
    for _ in s:
      max_list.append(ord(_))
    for i in range(ord("a"),max(max_list) + 2):
      s = s + chr(i)
      dfs(s)
      s = s[:len(s) - 1]
      
dfs("a")

Measured memory_bytes: 4428
#include<stdio.h>
#define MAXN 200000

long long x[MAXN],val[MAXN],rval[MAXN],shun[MAXN],ni[MAXN],w[MAXN];

long long _max(long long x,long long y){return x>y?x:y;}

int main(){
	
	long long ans=0,A=0;
	long long n,c;
	int i;
	scanf("%lld%lld",&n,&c);
	for(i=1;i<=n;i++){
		scanf("%lld%lld",&x[i],&w[i]);
		val[i]=val[i-1]+w[i];
		shun[i]=_max(val[i]-x[i],shun[i-1]);
	}
	for(i=n;i>=1;i--){
		rval[i]=rval[i+1]+w[i];
		ni[i]=_max(rval[i]-c+x[i],ni[i+1]);
	}
	A=0;
	for(i=n;i>=1;i--){
		A=_max(A,rval[i]-2*(c-x[i])+shun[i-1]);
		A=_max(A,ni[i]);
	}
	
	for(i=1;i<=n;i++){
		A=_max(A,val[i]-2*x[i]+ni[i+1]);
		A=_max(A,shun[i]);
	}
	
	printf("%lld",A);
	return 0;
}
	

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

#define rep(i,n) for(int i=0; i<(n); i++)
#define reps(i,x,n) for(int i=x; i<(n); i++)
#define rrep(i,n) for(int i=(n)-1; i>=0; i--)
#define all(X) (X).begin(),(X).end()
#define X first
#define Y second
#define pb push_back
#define eb emplace_back

using namespace std;
typedef long long int ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

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

template<class A, size_t N, class T> void Fill(A (&a)[N], const T &v){ fill( (T*)a, (T*)(a+N), v ); }

const ll INF = 1e9+7;


int main(){
	//ios_base::sync_with_stdio(false);
	int N;
	ll A[3][100005];

	cin >> N;
	rep(k,3) rep(i,N) cin >> A[k][i];
	rep(k,3) A[k][N] = INF;

	rep(k,3) sort(A[k], A[k]+N);

	ll dp[3][100005] = {};
	rep(i,N) dp[0][i] = 1;
	rep(k,2){
		int cur = 0;
		ll sum = 0;
		rep(i,N){
			while( A[k][cur] < A[k+1][i] ){
				sum += dp[k][cur];
				cur++;
			}
			dp[k+1][i] = sum;
		}
	}

	ll ans = 0;
	rep(i,N) ans += dp[2][i];

	cout << ans << endl;

	return 0;
}

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

using ll = long long;

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  while (true) {
    ll n, m;
    cin >> n >> m;
    if (n + m == 0) return 0;
    
    vector<ll> s(n);
    for (int i = 0; i < n; i++) cin >> s.at(i);
    
    ll l = s[0] - 1, r = 1e6 + 1;
    while (r - l > 1) {
      ll mid = (l + r) / 2, level = 1, battle = 0;
      while (true) {
        if (s.back() < level + mid) {
          battle++;
          break;
        }
        ll keep1, keep2;
        auto it = lower_bound(s.begin(), s.end(), level);
        if (it != s.end()) keep1 = *it;
        if (it != s.begin()) {
          it--;
          keep2 = *it;
        }
        else {
          keep2 = keep1;
        }
        ll up = max<ll>(1, mid - abs(level - keep2));
        if (keep1 < level + mid) up = max<ll>(up, mid - abs(level - keep1));
        level += up;
        battle++;
      }
      if (battle >= m) l = mid;
      else r = mid;
    }
    
    if (l == s[0] - 1) cout << -1 << '\n';
    else cout << l << '\n';
  }
}


Measured memory_bytes: 3900
/*
*/

#pragma GCC optimize("O3")
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <iostream>
#include <string>
#include <complex>
#include <math.h>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <stdio.h>
#include <stack>
#include <algorithm>
#include <list>
#include <ctime>

#include <memory.h>
#include <assert.h>

#define y0 sdkfaslhagaklsldk

#define y1 aasdfasdfasdf
#define yn askfhwqriuperikldjk
#define j1 assdgsdgasghsf
#define tm sdfjahlfasfh
#define lr asgasgash
#define norm asdfasdgasdgsd
#define have adsgagshdshfhds
#define ends asdgahhfdsfshdshfd

#define eps 1e-11
#define M_PI 3.141592653589793
#define bs 1000000007
#define bsize 512

#define ldouble long double
using namespace std;

long long INF = 1e9;

const int N = 300031;

int R,C,n;
vector<pair<int,int> > events;

bool on_border(int x,int y)
{
	return (x==0||x==R)||(y==0||y==C);
}

int normalize(int x,int y)
{
	if (x==0)
		return y;
	if (y==C)
		return C+x;
	if (x==R)
		return C+R+(C-y);
	return 2*(R+C)-x;
}

vector<pair<int,int> > segs;
map<int,int> maps;
vector<int> cords;

vector<int> compress(vector<int> v){
	sort(v.begin(),v.end());
	vector<int> ret;
	for (int i=0;i<v.size();i++)
	{
		if (i==0||v[i]!=v[i-1])
			ret.push_back(v[i]);
	}
	for (int i=0;i<ret.size();i++)
	{
		maps[ret[i]]=i;
	}
	return ret;
}

int t[N*4];

void build(int v,int tl,int tr)
{
	t[v]=1e9;
	if (tl==tr)
		return;
	int tm=tl+tr;
	tm/=2;
	build(v*2,tl,tm);
	build(v*2+1,tm+1,tr);
}

int get(int v,int tl,int tr,int l,int r)
{
	if (l>r)
		return 1e9;
	if (tl==l&&tr==r)
		return t[v];
	int tm=tl+tr;
	tm/=2;
	return min(get(v*2,tl,tm,l,min(r,tm)),get(v*2+1,tm+1,tr,max(tm+1,l),r));
}

void update(int v,int tl,int tr,int ps,int val)
{
	if (tl==tr)
	{
		t[v]=min(t[v],val);
		return;
	}
	int tm=tl+tr;
	tm/=2;
	if (ps<=tm)
		update(v*2,tl,tm,ps,val);
	else
		update(v*2+1,tm+1,tr,ps,val);
	t[v]=min(t[v*2],t[v*2+1]);
}

int main(){
	//freopen("tree.in","r",stdin);
	//freopen("tree.out","w",stdout);
	//freopen("input.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	ios_base::sync_with_stdio(0);
	//cin.tie(0);

	cin>>R>>C>>n;
	for (int i=0;i<n;i++)
	{
		int x1,y1,x2,y2;
		cin>>x1>>y1>>x2>>y2;
		if (!on_border(x1,y1))
			continue;
		if (!on_border(x2,y2))
			continue;
		int C1=normalize(x1,y1);
		int C2=normalize(x2,y2);
		if (C1>C2)
			swap(C1,C2);
//		cout<<C1<<"% "<<C2<<endl;
		segs.push_back(make_pair(C1,C2));
		cords.push_back(C1);
		cords.push_back(C2);
		// to do
	}

	cords=compress(cords);

	for (int i=0;i<segs.size();i++)
	{
		segs[i].first=maps[segs[i].first];
		segs[i].second=maps[segs[i].second];
	}

	for (int i=0;i<segs.size();i++)
	{
		events.push_back(make_pair(segs[i].second,segs[i].first));
	}

	sort(events.begin(),events.end());
	build(1,0,cords.size());

	int ok=1;

	for (int i=0;i<events.size();i++)
	{
		//cout<<events[i].first<< " "<<events[i].second<<endl;

		int val=get(1,0,cords.size(),events[i].second+1,events[i].first-1);
		if (val<events[i].second)
			ok=0;
		update(1,0,cords.size(),events[i].first,events[i].second);
	}

	if (ok)
		cout<<"YES"<<endl;
	else
		cout<<"NO"<<endl;

	cin.get(); cin.get();
	return 0;
}


Measured memory_bytes: 17100
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define loop(i, a, b) for(lli i=a; i<b; i++)
#define loopb(i, a, b) for(lli i=a; i>=b; i--)
#define fastio ios_base::sync_with_stdio(false); cin.tie(0)
#define pb push_back
typedef long long int lli;
typedef pair<lli, lli> pii;
typedef vector<lli> vll;
#define umap unordered_map
#define all(x) x.begin(), x.end()
// use to avoid collision
struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
// for pair in unordered_map
struct hash_pair {
    template <class T1, class T2>
    size_t operator()(const pair<T1, T2>& p) const
    {
        auto hash1 = hash<T1>{}(p.first);
        auto hash2 = hash<T2>{}(p.second);
        return hash1 ^ hash2;
    }
};
lli M = 1e9 + 7;
lli power(lli x, lli y){
    lli res = 1;
    x = x%M;
    while (y > 0) {
        if (y & 1)
            res = (res*x)%M ;
        y = y>>1;
        x = (x*x)%M ;
    }
    return res%M;
}
lli dp[3002][3002][2];
lli calc(vll& A, lli s, lli e, lli turn){
    lli n = A.size();
    if(s > e)
        return 0;
    else if(dp[s][e][turn] != -1)
        return dp[s][e][turn];
    lli ans = 0;
    if(turn == 0)
        ans = max(calc(A, s, e-1, 1-turn) + A[e], calc(A, s+1, e, 1-turn) + A[s]);
    else if(turn == 1)
        ans = min(calc(A, s, e-1, 1-turn) - A[e], calc(A, s+1, e, 1-turn) - A[s]);
    dp[s][e][turn] = ans;
    return ans;
}
lli solve(){
    lli n;
    cin>>n;
    vll A(n);
    lli sum = 0;
    loop(i, 0, n){
        cin>>A[i];
        sum += A[i];
    }
    memset(dp, -1, sizeof(dp));
    lli x = calc(A, 0, n-1, 0);
    cout<<x<<"\n";
    return 0;
}
int main(){
    fastio;
    lli t;
	// cin>>t;
    t = 1;
    while(t>0){ 
        t--;
        solve();
    }
}

Measured memory_bytes: 144612