akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <set>
#include <cstring>

using namespace std;
// ascending order
#define vsort(v) sort(v.begin(), v.end())
// descending order
#define vsort_r(v) sort(v.begin(), v.end(), greater<int>())
#define vunique(v) unique(v.begin(), v.end())
#define mp make_pair
#define ts(x) to_string(x)
#define rep(i, a, b) for(int i = (int)a; i < (int)b; i++)
#define repm(i, a, b) for(int i = (int)a; i > (int)b; i--)
#define bit(a) bitset<8>(a)
#define des_priority_queue priority_queue<int, vector<int>, greater<int> >
#define all(v) (v).begin(), (v).end()
typedef long long ll;
typedef pair<int, int> P;
const ll INF = 1ll << 60;

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

int N, A[21][21];
int dp[22][1 << 21];
const int mod = 1e9 + 7;

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

    cin >> N;
    rep(i, 0, N) rep(j, 0, N) cin >> A[i][j];

    dp[0][0] = 1;

    rep(i, 0, N) {
        for(int mask = 0; mask < 1 << N; mask++) {
            if(__builtin_popcount(mask) == i) {
                rep(j, 0, N) {
                    if(!(mask & 1 << j) and A[i][j]) {
                        (dp[i + 1][mask | 1 << j] += dp[i][mask]) %= mod;
                    }
                }
            }
        }

    }

    cout << dp[N][(1 << N) - 1] << endl;

}


Measured memory_bytes: 162048
#include<iostream>
#include<cmath>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;

bool is_integer( double x )
{
    return std::floor(x)==x;
}

int main()
{
    int a,b;
    cin>>a>>b;
    int i=1;
    while (i<10000)
    {
        if(int(i*0.08)==a && int(i*0.1)==b)
        {
            break;
        }
        i++;
    }
    if(i==10000)i=-1;
    cout<<i<<endl;

    return 0;
}

Measured memory_bytes: 256
#LRUD
#odd rud
#even lud
a = input()
for i in range(len(a)):
    if i%2 == 0:
        if a[i] == "L":
            print("No")
            quit()
    else:
        if a[i] == "R":
            print("No")
            quit()
print("Yes")

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

using ll = long long;

const int INF = 1001001001;
const ll INF_LL = 1001001001001001001LL;

int main(void){
  int n; cin >> n;
  ll div = 1e9;
  div += 7;

  ll ans;
  ll p10 = 1,p9 = 1,p8 = 1;
  rep(i,n){
    p10 *= 10;
    p9 *= 9;
    p8 *= 8;
    p10 %= div;
    p9 %= div;
    p8 %= div;
  }
  p9 *= 2;
  p9 %= div;

  ans = p10-p9+p8;
  ans %= div;
  ans = (ans+div)%div;
  cout << ans << endl;
  
  return 0;
}


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

typedef long long ll;
const int N = (int)2e5 + 5;
const ll mod = (ll)1e9 + 7;

int n, m, a, b;
ll fac[N], facinv[N];
ll inv[N];

ll fp(ll x, ll k){
    if(k == 0) return 1;
    ll hf = fp(x, k/2);
    return k % 2 ? hf * hf % mod * x % mod: hf * hf % mod;
}

ll comb(int n, int k){
    return fac[n] * facinv[k] % mod * facinv[n - k] % mod;
}


int main(){
    inv[1] = 1;
    for(int i = 2; i < N; i++) inv[i] = (mod - (mod / i) * inv[mod % i] % mod) % mod;
    fac[0] = 1;
    for(int i = 1; i <= N-1; i++) fac[i] = fac[i-1] * i % mod;
    facinv[N-1] = fp(fac[N-1], mod - 2);
    for(int i = N-1 - 1; i >= 0; i--) facinv[i] = facinv[i+1] * (i+1) % mod;

    cin >> n >> m >> a >> b;
    ll res = comb(n + m - 2, n - 1);
    for(int i = 0; i < b; i++) {
        res -= comb(n - 1 - a + i, i) * comb(m - 1 - i + a - 1, a - 1) % mod;
        res %= mod;
    }
    cout << (res + mod) % mod << endl;

}


Measured memory_bytes: 4992
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <vector>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <map>
#include <queue>
#define rep(i,n) for (int i=0;i<(n);i++)

using namespace std;

int main() {
	string s;
	string front = "";

	cin >> s;
	int q;
	cin >> q;
	int re = 0;

	for (int i = 0;i < q;i++) {
		int t;
		cin >> t;
		if (t == 1) {
			re++;
		}
		else {
			int f;
			char c;
			cin >> f >> c;
			if (re % 2 == 0) {
				if (f == 1) {
					front += c;
				}
				else {
					s += c;
				}
			}
			else
			{
				if (f == 1) {
					s += c;
				}
				else {
					front += c;
				}
			}
		}
	}
	reverse(front.begin(), front.end());
	s = front + s;

	if (re % 2 == 1) {
		reverse(s.begin(), s.end());
	}

	cout << s << endl;
	return 0;
}

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

int main(){
    string s,t;
    cin>>s>>t;
    int n,m;
    n = s.length();
    m = t.length();

    int dp[n+1][m+1];

    for(int i=0; i<=n; i++){
        for(int j=0; j<=m; j++){
            if(i == 0 || j == 0){
                dp[i][j]=0;
            }
            else if(s[i-1] == t[j-1]){
                dp[i][j] = 1 + dp[i-1][j-1];
            }
            else{
                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
            }
        }
    }

    string res = "";
    int i=n, j=m;

    while(i > 0 && j > 0){
        if(s[i-1] == t[j-1]){
            res = res + s[i-1];
            j--;
            i--;
        }
        else if(dp[i-1][j] > dp[i][j-1]){
            i--;
        }
        else{
            j--;
        }
    }
    //cout<<dp[n][m]<<endl;

    reverse(res.begin(), res.end());

    cout<<res<<endl;
}


Measured memory_bytes: 35456
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<utility>
#include<algorithm>
#include<cmath>
#include<climits>
using namespace std;

int main(){
	int n;
	cin >> n;
	set<int> x;
	for(int i=0; i<n; i++){
		int d;
		cin >> d;
		x.insert(d);
	}
	cout << x.size() << '\n';
	return 0;
}

Measured memory_bytes: 256
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner sc = new Scanner(System.in);
		String S = sc.nextLine();
		//1234
		String YY = S.substring(0, 2);
		String MM = S.substring(2, 4);

		int yy = Integer.parseInt(YY);
		int mm = Integer.parseInt(MM);

		//YYMM
		//yy>12 && 01 <= MM <= 12

		//MMYY
		//13 > yy && MM >12

		//AMBIGUOUS
		//01 <= MM <= 12 && 12 >= yy

		//NA
		// else
		if((yy > 12  || yy == 0)&& (1 <= mm && mm <=12)){//
			System.out.println("YYMM");
		}else if((12 >= yy && yy > 0) && (mm > 12 || mm == 0)) {//0100
			System.out.println("MMYY");
		}else if(12 >= yy && (1 <= mm && mm <=12) ) {
			System.out.println("AMBIGUOUS");
		}else {
			System.out.println("NA");
		}


	}

}


Measured memory_bytes: 35680
import java.util.*;
import java.io.*;
import java.math.BigInteger;

class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int max = a + b;
        max = Math.max(a - b, max);
        max = Math.max(a * b, max);

        System.out.println(max);



    }
}

Measured memory_bytes: 23764
import numpy as np

N, M = map(int, input().split())

S = []
for n in range(N):
    S.append(list(map(int, input().split())))

S = np.array(S)

S = S[np.argsort(S[:, 0])]

count = 0
yen = 0
for s in S:
    if count + s[1] < M:
        yen += s[0] * s[1]
        count += s[1]
    else:
        yen += s[0] * (M-count)
        break

print(yen)


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

using namespace std;
using llong = long long;
using P = pair<llong, llong>;

#define BE(x) x.begin(), x.end()

const llong inf = llong(1e18)+7;
const llong mod = 1e9+7;

int main(){
	int N;
	vector<int> A[2];

	cin >> N;
	A[0].resize(N);
	A[1].resize(N);
	for(int i = 0; i < 2; i++)
		for(int j = 0; j < N; j++)
			cin >> A[i][j];

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

	cout << ans[1][N-1] << endl;

	return 0;
}

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

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

typedef int _loop_int;
#define REP(i,n) for(_loop_int i=0;i<(_loop_int)(n);++i)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i)
#define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i)

#define DEBUG(x) cout<<#x<<": "<<x<<endl
#define DEBUG_VEC(v) cout<<#v<<":";REP(i,v.size())cout<<" "<<v[i];cout<<endl
#define ALL(a) (a).begin(),(a).end()

#define CHMIN(a,b) a=min((a),(b))
#define CHMAX(a,b) a=max((a),(b))

// mod
const ll MOD = 1000000007ll;
#define FIX(a) ((a)%MOD+MOD)%MOD

// floating
typedef double Real;
const Real EPS = 1e-11;
#define EQ0(x) (abs(x)<EPS)
#define EQ(a,b) (abs(a-b)<EPS)
typedef complex<Real> P;

// pos, set
ll dp[52][1<<17];

int n,x,y,z;
int main(){
  scanf("%d%d%d%d",&n,&x,&y,&z);
  const int len = x+y+z;
  const int sz = 1<<(x+y+z);
  int ok[20], nxt[20];
  ll ans = 0;
  dp[0][1] = 1;
  REP(i,n){
    ans *= 10;
    ans %= MOD;
    FOR(d,1,11){
      REP(msk,sz){
        if(!dp[i][msk])continue;
        int nmsk = 1;
        bool flag = false;
        REP(j,len){
          if(j+d > len)break;
          if(!((msk>>j)&1))continue;
          if(j < x     && j+d > x)continue;
          if(j < x+y   && j+d > x+y)continue;
          if(j < x+y+z && j+d > x+y+z)continue;
          if(j+d == x+y+z){
            ans += dp[i][msk];
            ans %= MOD;
            flag = true;
          }else{
            nmsk |= 1<<(j+d);
          }
        }
        if(!flag){
          dp[i+1][nmsk] += dp[i][msk];
          dp[i+1][nmsk] %= MOD;
        }
      }
    }
  }
  printf("%lld\n",ans);
  return 0;
}


Measured memory_bytes: 30336
#include <bits/stdc++.h>
using namespace std;
int main(){
  int s;
  cin >> s;
  int count=1;
  while(s!=1&&s!=2&&s!=4){
    count++;
    if(s%2) s=3*s+1;
    else s/=2;
  }
  cout << count+3 << endl;
}

Measured memory_bytes: 3588
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <list>
#include <vector>
#include <complex>
#include <utility>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <climits>
#include <bitset>
#include <ctime>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <numeric>
#include <tuple>
#include <sstream>
#include <fstream>

using namespace std;
#define REP(i, n) for (int (i) = 0; (i) < (n); (i)++)
#define FOR(i, a, b) for (int (i) = (a); (i) < (b); (i)++)
#define RREP(i, a) for(int (i) = (a) - 1; (i) >= 0; (i)--)
#define FORR(i, a, b) for(int (i) = (a) - 1; (i) >= (b); (i)--)
#define DEBUG(C) cerr << #C << " = " << C << endl;
using LL = long long;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<LL>;
using VVL = vector<VL>;
using VD = vector<double>;
using VVD = vector<VD>;
using PII = pair<int, int>;
using PDD = pair<double, double>;
using PLL = pair<LL, LL>;
using VPII = vector<PII>;
#define ALL(a) begin((a)), end((a))
#define RALL(a) rbegin((a)), rend((a))
#define SORT(a) sort(ALL((a)))
#define RSORT(a) sort(RALL((a)))
#define REVERSE(a) reverse(ALL((a)))
#define MP make_pair
#define FORE(a, b) for (auto &&a : (b))
#define FIND(s, e) ((s).find(e) != (s).end())
#define EB emplace_back

const int INF = 1e9;
const int MOD = INF + 7;
const LL LLINF = 1e18;

/**
* Binary_Indexed_Tree(BIT)
* Fenwick Tree
* 1-indexed!!!
*/
template<typename T>
class BIT {
private:
    std::vector<T> bit;
    const int N;
public:
    BIT() : N(-1) {}
    BIT(int n) : N(n), bit(n + 1, 0) {}
    //bit[point]???num??????
    void add(int point, T num) {
        assert(N != -1 && 0 <= point && point <= N);
        while (point <= N) {
            bit[point] += num;
            point += point & -point;
        }
    }
    //point?????§?????????????????????
    T sum(int point) {
        assert(N != -1 && 0 <= point && point <= N);
        T res = 0;
        while (point > 0) {
            res += bit[point];
            point -= point & -point;
        }
        return res;
    }
};

const int MAX = 1e5 + 5;

signed main(void) {
    int n, q;
    cin >> n >> q;
    BIT<int> t(n);
    while (q--) {
        int c, x, y;
        scanf("%d%d%d", &c, &x, &y);
        if (c) {
            cout << t.sum(y) - t.sum(x - 1) << endl;
        } else {
            t.add(x, y);
        }
    }
}

Measured memory_bytes: 3412
Scanf.scanf "%s" (fun s ->
    let n = String.length s in

    let rec loop i acc =
        if i = n then acc / 2 else
            if s.[i] = 'g' then loop (i + 1) (acc + 1)
                           else loop (i + 1) (acc - 1)
    in
    loop 0 0 |> Printf.printf "%d\n"
)

Measured memory_bytes: 4184
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;

int main(){
  int H, W, D; cin >> H >> W >> D;
  pair<int, int> p[90010];
  rep(i, H){
    rep(j, W){
      int a; cin >> a; a--;
      p[a] = {i, j};
    }
  }
  ll tmp[90010] = {};
  rep(i, W*H){
    if(i>=D) tmp[i] = abs(p[i].first-p[i-D].first) + abs(p[i].second-p[i-D].second);
  }
  rep(i, W*H){
    if(i>=D) tmp[i] += tmp[i-D];
  }
  int Q; cin >> Q;
  rep(i, Q){
    int l, r; cin >> l >> r; l--; r--;
    cout << tmp[r]-tmp[l] << endl;
  }
}

Measured memory_bytes: 2560
#define IN(x,s,g) ((x) >= (s) && (x) < (g))
#define ISIN(x,y,w,h) (IN((x),0,(w)) && IN((y),0,(h)))

#include <queue>
#define REP(i,n) for(int i=0; i<(int)(n); i++)

#include <set>
#include <cstdio>
inline int getInt(){ int s; scanf("%d", &s); return s; }

using namespace std;

int ob[5][5];
int s[5];

int simulate(int b[5][5]){
  int bornus = 1;
  int ret = 0;

  bool flag = true;
  while(flag){
    flag = false;
    int del[5][5] = {{0}};

    REP(i,5) REP(j,5){
      if(b[i][j] != -1){
        if(i + 2 < 5 && b[i][j] == b[i + 1][j] && b[i][j] == b[i + 2][j]){
          del[i][j] = del[i + 1][j] = del[i + 2][j] = 1;
          flag = true;
        }
        if(j + 2 < 5 && b[i][j] == b[i][j + 1] && b[i][j] == b[i][j + 2]){
          del[i][j] = del[i][j + 1] = del[i][j + 2] = 1;
          flag = true;
        }
      }
    }

    REP(i,5) REP(j,5) if(del[i][j]){
      ret += bornus * s[b[i][j]];
      b[i][j] = -1;
    }

    REP(k,4){
      REP(i,4){
        REP(j,5) if(b[i + 1][j] == -1){
          swap(b[i][j], b[i + 1][j]);
        }
      }
    }

    bornus++;
  }

  return ret;
}

const int _dx[] = {0,1,0,-1};
const int _dy[] = {-1,0,1,0};

int main(){
  while(int nn = getInt() + 1){
    const int n = nn - 1;

    REP(i,5) REP(j,5)
      ob[i][j] = getInt() - 1;
    REP(i,5) s[i] = getInt();

    int ans = 0;

    {
      int bb[5][5];
      REP(i,5) REP(j,5)
        bb[i][j] = ob[i][j];
      ans = max(ans, simulate(bb));
    }

    REP(x,5) REP(y,5){
      REP(ss, 1 << (2 * n)){
        int sss = ss;
        int bb[5][5];
        int xx = x;
        int yy = y;

        REP(i,5) REP(j,5)
          bb[i][j] = ob[i][j];

        REP(i,n){
          const int ns = sss % 4; sss /= 4;
          const int xxx = xx + _dx[ns];
          const int yyy = yy + _dy[ns];

          if(!ISIN(xxx, yyy, 5, 5)) break;

          swap(bb[yyy][xxx], bb[yy][xx]);

          int bbb[5][5];
          REP(ii,5) REP(jj,5) bbb[ii][jj] = bb[ii][jj];
          ans = max(ans, simulate(bbb));

          xx = xxx; yy = yyy;
        }
      }
    }

    printf("%d\n", ans);
  }

  return 0;
}

Measured memory_bytes: 1032
#include<stdio.h>
#include<stdlib.h>
int main(){
    int i,j,n;
    int a[3][3];
    for(i=0;i<3;i++){
        for(j=0;j<3;j++)
            scanf("%d",&a[i][j]);
    }
    scanf("%d",&n);
    int b[n];
    for(i=0;i<n;i++){
        scanf("%d",&b[i]);
        for(j=0;j<3;j++){
            for(int k=0;k<3;k++)
                if(a[j][k]==b[i])
                    a[j][k]=0;
        }
    }
    int ans=0;
    if(a[0][0]==a[0][1]&&a[0][0]==a[0][2]&&a[0][0]==0) ans=1;
    if(a[0][0]==a[1][0]&&a[0][0]==a[2][0]&&a[0][0]==0) ans=1;
    if(a[0][0]==a[1][1]&&a[0][0]==a[2][2]&&a[0][0]==0) ans=1;
    if(a[1][0]==a[1][1]&&a[1][0]==a[1][2]&&a[1][0]==0) ans=1;
    if(a[2][0]==a[2][1]&&a[2][0]==a[2][2]&&a[2][0]==0) ans=1;
    if(a[0][1]==a[1][1]&&a[0][1]==a[2][1]&&a[0][1]==0) ans=1;
    if(a[0][2]==a[1][2]&&a[0][2]==a[2][2]&&a[0][2]==0) ans=1;
    if(a[2][0]==a[1][1]&&a[2][0]==a[0][2]&&a[2][0]==0) ans=1;
    if(ans==1) printf("Yes\n");
    else printf("No\n");
    return 0;
}

Measured memory_bytes: 128
#include<stdio.h>
int main(){
    
    int n,i,a[200000],t[200000];
    scanf("%d",&n);
    for(i=0;i<n;i++)
        t[i]=0;
    for(i=0;i<n;i++){
        scanf("%d",&a[i]);
        t[a[i]-1]++;
    }
    for(i=0;i<n;i++)
        printf("%d\n",t[i]);
    return 0;
    
}


Measured memory_bytes: 3268
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {

	sc.Split(bufio.ScanWords)

	var A, B, M int
	A = nextInt()
	// fmt.Scan(&A, &B, &M)
	// alist := make([]int, A)
	// blist := make([]int, B)
	alist := make([]int, A)
	B = nextInt()
	blist := make([]int, B)
	M = nextInt()

	minA := 0
	minB := 0

	var n int

	for i := 0; i < A; i++ {
		// fmt.Scan(&n)
		n = nextInt()
		alist[i] = n
		if minA > n || minA == 0 {
			minA = n
		}
	}

	for i := 0; i < B; i++ {
		// fmt.Scan(&n)
		n = nextInt()
		blist[i] = n
		if minB > n || minB == 0 {
			minB = n
		}
	}

	res := minA + minB
	var x, y, z int
	for i := 0; i < M; i++ {
		// fmt.Scan(&x, &y, &z)
		x = nextInt()
		y = nextInt()
		z = nextInt()

		if res > alist[x-1]+blist[y-1]-z {
			res = alist[x-1] + blist[y-1] - z
		}
	}

	fmt.Println(res)
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}


Measured memory_bytes: 4992
#include<cstdio>
#include<algorithm>
using namespace std;
char p[80];
int n, K, chk[80], Loc[40], C[40], F[150], InvF[150], Mod = 1000000007;
int D[40][40], TD[40][40]; // 한 블럭의 크기, 블럭의 개수, 쓴거의 개수

int Pow(int a, int b) {
	int r = 1;
	while (b) {
		if (b & 1)r = 1ll * r*a%Mod;
		a = 1ll * a*a%Mod; b >>= 1;
	}
	return r;
}
int Comb(int n, int r) {
	return 1ll * F[n] * InvF[r] % Mod*InvF[n - r]%Mod;
}

int Do(int A, int B) { // R* : A, RBxx : B
	int i, c1 = 0, c2 = 0, j, k, ii, jj;
	if (!A && !B)return 1;
	for (i = 0; i < K; i++) {
		chk[i] = 0;
		if (p[i] == 'r' && c1 < B) {
			chk[i] = 1;
			c1++;
		}
		if (p[i] == 'b' && c2 < c1) {
			chk[i] = 1;
			c2++;
			Loc[c2] = i;
		}
	}
	if (c1 < B || c2 < B)return 0;
	c1 = 0;
	for (i = 0; i < K; i++) {
		if (p[i] == 'r' && !chk[i] && c1 < A) {
			chk[i] = 1;
			c1++;
		}
	}
	if (c1 < A)return 0;
	for (i = 1; i <= B; i++) {
		C[B-i+1] = 0;
		for (j = Loc[i]; j < K; j++)if (!chk[j])C[B-i+1]++;
	}
	for (i = 0; i < 40; i++)for (j = 0; j < 40; j++)D[i][j] = TD[i][j] = 0;
	D[0][0] = InvF[A];

	for (i = 0; i <= n / 2; i++) {
		for (j = 0; j < 40; j++) {
			for (k = 0; k < 40; k++) {
				if (!D[j][k])continue;
				for (ii = 0;; ii++) {
					int s = (ii*i + k);
					if (ii+j > B || s * 2 + A + B + (A + B - 1) > n || C[j+ii] < s)break;
					TD[j + ii][s] = (TD[j + ii][s] + 1ll * D[j][k] * InvF[ii]) % Mod;
				}
			}
		}
		for (j = 0; j < 40; j++)for (k = 0; k < 40; k++) {
			D[j][k] = TD[j][k];
			TD[j][k] = 0;
		}
	}
	int r = 0;
	for (i = 0; i < 40; i++) {
		int c = (A + B + A + B - 1 + i * 2);
		int t = c + B * 2 + 2;
		if (!D[B][i] || n-c < 0)continue;
		r = (r + 1ll * D[B][i] * F[A+B] % Mod * Comb(t + (n - c) - 1, (n - c)))%Mod;
	}
	return r;
}
int main() {
	int i, j, res = 0;
	F[0] = 1;
	for (i = 1; i <= 142; i++)F[i] = 1ll * F[i - 1] * i%Mod;
	for (i = 0; i <= 142; i++)InvF[i] = Pow(F[i], Mod - 2);
	scanf("%d%d", &n, &K);
	scanf("%s", p);
	for (i = 0; i <= (n+1)/2; i++) {
		for (j = 0; i + j <= (n + 1) / 2; j++) {
			res = (res + Do(i, j))%Mod;
		}
	}
	printf("%d\n", res);
}

Measured memory_bytes: 128
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> ii;
const int N=2e3+20;
ll n,W,w1; 
struct node{
	ll w,v;
}a[N];
bool cmp(node a,node b)
{
	if(a.w==b.w)
		return a.v>b.v;
	return a.w<b.w;
}
vector<ll> p[N];
ll ans,pre[N][N];
void dfs(int cur,ll res,ll cnt)
{
	if(cnt>W)
		return;
	if(cur==4)
	{
		ans=max(ans,res);
		return;
	}
	dfs(cur+1,res,cnt);//choose zero
	for(int i=0;i<p[cur].size();i++)
		dfs(cur+1,res+pre[cur][i],cnt+(w1+cur)*(i+1));//
	
}
int main()
{
	while(cin>>n>>W)
	{
		for(int i=0;i<4;i++)
			p[i].clear();
		ans=0;
		memset(pre,0,sizeof(pre));
		w1=1e9;
		for(int i=1;i<=n;i++)
			cin>>a[i].w>>a[i].v,w1=min(w1,a[i].w);
		sort(a+1,a+1+n,cmp);
		for(int i=1;i<=n;i++)
			p[a[i].w-w1].push_back(a[i].v);
		for(int i=0;i<4;i++)
			for(int j=0;j<p[i].size();j++)
			{
				pre[i][j]=p[i][j];
				if(j)
					pre[i][j]+=pre[i][j-1];
			}
		dfs(0,0,0);
		cout<<ans<<endl;
	}
	return 0;
}

Measured memory_bytes: 32128
#[allow(unused_macros)]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules ! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

#[allow(dead_code)]
pub const M: u64 = 1_000_000_007;

fn main() {
    input! {
        n: usize,
        a: [u64; n]
    }

    let mut frac = vec![0u64;n];
    for i in 0..n {
        frac[i] = fact(n as u64) * modinv(i as u64 + 1, M);
    }
    let frac_csum = Cum::new(&frac);
    let mut ret = 0u64;
    for i in 0..n {
        let ptn = (frac_csum.sum(0, i+1) + frac_csum.sum(1,n-i)) % M;
        ret += a[i] * ptn % M;
        ret %= M;
    }
    println!("{}", ret);
}

fn fact(n: u64) -> u64 {
    if n == 1 {1}
    else {n * fact(n-1) % M}
}

#[derive(Debug)]
#[allow(dead_code)]
struct Cum {
    s: Vec<u64>,
}
#[allow(dead_code)]
impl Cum {
    fn new(a: &Vec<u64>) -> Cum {
        let mut s = vec![0; a.len() + 1];
        for i in 0..a.len() {
            s[i + 1] = (s[i] + a[i]) % M;
        }
        Cum { s: s }
    }
    #[doc = " [l,r)"]
    fn sum(&self, l: usize, r: usize) -> u64 {
        sub_mod(self.s[r], self.s[l], M)
    }
}

fn sub_mod(a: u64, b: u64, m: u64) -> u64 {
    let mut tmp = (a as i64 - b as i64) % m as i64;
    if tmp < 0 {
        tmp += m as i64;
    }
    tmp as u64
}


#[doc = " a / b modulo m == a * modinv(b, m) % m"]
#[allow(dead_code)]
fn modinv(a_: u64, m_: u64) -> u64 {
    let m = m_ as i64;
    let mut a = a_ as i64;
    let mut b = m as i64;
    let mut u = 1;
    let mut v = 0;
    while b != 0 {
        let t = a / b;
        a -= t * b;
        std::mem::swap(&mut a, &mut b);
        u -= t * v;
        std::mem::swap(&mut u, &mut v);
    }
    u %= m;
    if u < 0 {
        u += m
    };
    u as u64
}

Measured memory_bytes: 7932
#include <bits/stdc++.h>
#define int long long
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define F first
#define S second

using namespace std;
typedef pair<int,int> P;

const int MOD=1000000007;
int INF=100100100100100;

signed main(){
  int n,k;cin>>n>>k;
  cout<<n-k+1<<endl;
  return 0;
}

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

#define CIN1(a) long long a;cin >> a;
#define CIN2(a,b) long long a,b;cin >> a >> b;
#define CIN3(a,b,c) long long a,b,c;cin >> a >> b >> c;
#define rep(i,n) for(int i=0,i##_len=(n); i<i##_len; ++i)

int main(){
    CIN2(a,b)
    string s;
    if((a&1)&&(b&1)){
        s = "Yes";
    }else{
        s = "No";
    }
    cout << s << endl;
}

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

signed main(void){
    int k,n; cin >> k >> n;
    vector<int>a(n);
    int first; cin >> first;
    int before = first;
    int tmp; 
    for(int i=0;i<n-1;i++){
        cin >> tmp;
        a.push_back(tmp-before);
        before = tmp;
    }
    a.push_back(k-tmp+first);
    sort(a.begin(),a.end());
    int ans = accumulate(a.begin(),a.end()-1,(int)0);
    cout << ans << endl;
    return 0;
}

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

const int MAXN = 1e5 + 5;
int dp[MAXN], h[MAXN];

int main() {
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++)
        cin >> h[i];
    for(int i = 2; i <= n; i++) {
        dp[i] = dp[i - 1] + abs(h[i] - h[i - 1]);
        if(i > 2)
            dp[i] = min(dp[i], dp[i - 2] + abs(h[i] - h[i - 2]));
    }
    cout << dp[n] << endl;
}

Measured memory_bytes: 1024
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>

using namespace std;

int main() {

	int W, H, N;
	int x[100], y[100], a[100];
	int grid[105][105];

	cin >> W >> H >> N;
	for (int i = 0; i < N; i++) {
		cin >> x[i] >> y[i] >> a[i];
	}

	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			grid[i][j] = 0;
		}
	}

	for (int i = 0; i < N; i++) {
		if (a[i] == 1) {
			for (int j = 0; j < H; j++) {
				for (int k = 0; k < x[i]; k++) {
					grid[j][k] = 1;
				}
			}
		}

		if (a[i] == 2) {
			for (int j = 0; j < H; j++) {
				for (int k = x[i]; k < W; k++) {
					grid[j][k] = 1;
				}
			}
		}

		if (a[i] == 3) {
			for (int j = 0; j < y[i]  ; j++) {
				for (int k = 0; k < W; k++) {
					grid[j][k] = 1;
				}
			}
		}

		if (a[i] == 4) {
			for (int j = y[i]; j < H; j++) {
				for (int k = 0; k < W; k++) {
					grid[j][k] = 1;
				}
			}
		}
	}

	int cnt = 0;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (grid[i][j] == 0) cnt++;
		}
	}

	cout << cnt << endl;

	return 0;
}

Measured memory_bytes: 256
def main():
    X, K, D = map(int, input().split())
    if abs(X) >= K*D:
        if X <= 0:
            print(abs(X+K*D))
        else:
            print(X-K*D)
    else:
        K -= abs(X) // D
        if K % 2 == 0:
            print(abs(X)%D)
        else:
            print(D-abs(X)%D)

if __name__ == "__main__":
    main()

Measured memory_bytes: 61856
import java.lang.*;
import java.io.*;
import java.util.*;

class Main{
	public static void main(String args[]) throws Exception{
		FScanner sc=new FScanner();
		int n=sc.readInt();
		double[] ta=sc.readDoubleL();
		double t=ta[0];
		double a=ta[1];
		double[] ht=sc.readDoubleL();
		double[] w=new double[n];
		
		for(int i=0; i<ht.length; i++){
			w[i]=Math.abs(a-(t-(ht[i]*0.006)));
		}
		
		int ans=0;
		double mx=Double.MAX_VALUE;
		
		for(int i=0; i<w.length; i++){
			if(mx>w[i]){
				mx=w[i];
				ans=i;
			}
		}
		System.out.println(ans+1);
	}

	static void disp(int[] data){
		for(int i=0; i<data.length; i++){
				System.out.printf("%d ",data[i]);
		}
			System.out.println();
	}
	
	static void disp(String[] data){
		for(int i=0; i<data.length; i++){
				System.out.printf("%s ",data[i]);
		}
			System.out.println();
	}
	
	static void disp(long[] data){
		for(int i=0; i<data.length; i++){
				System.out.printf("%d ",data[i]);
		}
			System.out.println();
	}
	
	static class FScanner{
		BufferedReader read=null;
		StringTokenizer tok=null;
		Scanner sc;
		FScanner() throws FileNotFoundException{
			sc=new Scanner(System.in);
		}
		boolean hasNextLine(){
			boolean has=true;
			if(!sc.hasNextLine()){
				has=false;
			}
			return has;
		}
		int readInt(){
			String buf=sc.nextLine();
			return Integer.parseInt(buf);
		}
		long readLong(){
			long i=Long.parseLong(sc.nextLine());
			return i;
		}
		int[] readIntL(){
			String[] buf=sc.nextLine().split(" ");
			int[] num=new int[buf.length];
			for(int i=0; i<buf.length; i++){
				num[i]=Integer.parseInt(buf[i]);
			}
			return num;
		}
		
		double[] readDoubleL(){
			String[] buf=sc.nextLine().split(" ");
			double[] num=new double[buf.length];
			for(int i=0; i<buf.length; i++){
				num[i]=Double.parseDouble(buf[i]);
			}
			return num;
		}
		
		String readString(){
			return sc.nextLine();
		}
		String[] readStringL(String dlm){
			String[] s=sc.nextLine().split(dlm);
			return s;
		}
	}
}


Measured memory_bytes: 23508
#include <iostream>
#include <cmath>
#include <climits>
#include <string>
#include <numeric>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <set>

using namespace std;
using ll = long long;

template<typename T> void print(T t) { cout << t << endl; }
ll MOD = 1000000007;

ll calc(const vector<ll> As, ll L) {
	ll ans = 0;
	for (int lo : As) {
		ans += (lo + L - 1) / L - 1;
	}
	return ans;
}

int main() {
	int N, K;
	ll minl = 1, maxl = 0;
	cin >> N >> K;
	vector <ll > As(N);
	for (auto &A : As) {
		cin >> A;
		maxl = max(maxl, A);
	}
	
	while(maxl > minl+1) {
		int judge =  calc(As, (maxl + minl) / 2)-K;
		if (judge > 0) {//too small
			minl = (maxl + minl) / 2;
		}
		else{
			maxl = (maxl + minl) / 2;
		}
	}

	//recheck
	ll l = maxl;
	for (l = max(1ll,maxl - 10); l < maxl + 10; l++) {
		if (calc(As, l) <= K)break;
	}
	print(l);
}

Measured memory_bytes: 6356
#![allow(unused_imports)]

#[macro_use]
mod _input {
    use std::fmt;
    use std::io::{self, Read};
    use std::str::{self, FromStr};

    macro_rules! input {
        ($($name:ident : $t:tt),*,) => {
            input!($($name: $t),*)
        };
        ($($name:ident : $t:tt),*) => {
            let mut _scanned = ::_input::Scanned::new(::std::io::stdin(), 1024);
            $(
                let $name = _read_value!(_scanned, $t);
            )*
        };
    }

    macro_rules! _read_value {
        ($scanned:expr, ($($t:tt),*)) => {
            ($(_read_value!($scanned, $t)),*)
        };
        ($scanned:expr, [$t:tt; $n:expr]) => {
            (0..$n).map(|_| _read_value!($scanned, $t)).collect::<Vec<_>>()
        };
        ($scanned:expr, _bytes) => {
            _read_value!($scanned, String).into_bytes()
        };
        ($scanned:expr, _1based) => {
            _read_value!($scanned, usize) - 1
        };
        ($scanned:expr, $t:ty) => {
            $scanned.next::<$t>()
        };
    }

    #[derive(Default)]
    pub struct Scanned {
        buf: Vec<u8>,
        pos: usize,
    }

    impl Scanned {
        pub fn new<R: Read>(mut input: R, estimated: usize) -> Self {
            let mut buf_ = Vec::with_capacity(estimated);
            let _ = io::copy(&mut input, &mut buf_).unwrap();
            if buf_.last() != Some(&b'\n') {
                buf_.push(b'\n');
            }
            debug_assert!(str::from_utf8(&buf_).is_ok());
            debug_assert!(buf_.iter().all(|&c| u32::from(c) <= 0x7F));
            Scanned { buf: buf_, pos: 0 }
        }

        #[inline]
        pub fn next<T: FromStr>(&mut self) -> T
        where
            T::Err: fmt::Debug,
        {
            let mut start = None;
            loop {
                match (self.buf[self.pos], start.is_some()) {
                    (b' ', true) | (b'\n', true) => break,
                    (_, true) | (b' ', false) | (b'\n', false) => self.pos += 1,
                    (_, false) => start = Some(self.pos),
                }
            }
            let target = &self.buf[start.unwrap()..self.pos];
            unsafe { str::from_utf8_unchecked(target) }.parse().unwrap()
        }
    }
}

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{self, BufWriter, Read, Stderr, StderrLock, Stdout, StdoutLock, Write};
use std::num::{ParseFloatError, ParseIntError};
use std::ops::{
    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
    Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
};
use std::str::{self, FromStr};
use std::{char, cmp, f32, f64, fmt, i16, i32, i64, i8, mem, thread, u16, u32, u64, u8};

fn main() {
    input! {
        k: u64,
        a: u64,
        b: u64,
    }

    let r = 1 + cmp::min(a - 1, k);
    let k = k - r + 1;
    let d = cmp::max(cmp::max(b, a) - a, 2);
    let (r, k) = (r + d * (k / 2), k % 2);
    let r = r + k;
    println!("{}", r);
}


Measured memory_bytes: 4352
#include <cstdio>
using namespace std;

int search(int A[], int n, int key) {
    int hi = n;
    int lo = 0;
    int mid;
    while (lo + 1 < hi) {
        mid = lo + (hi - lo) / 2;
        if (key < A[mid]) hi = mid;
        else lo = mid;
    }
    return A[lo] == key;
}

int main(void) {
    int n, q, k, i;
    int A[150000];
    int c = 0;

    scanf("%d", &n);
    for (i = 0; i < n; i++) scanf("%d", &A[i]);

    scanf("%d", &q);
    for (i = 0; i < q; i++) {
        scanf("%d", &k);
        if (search(A, n, k)) c++;
    }

    printf("%d\n", c);

    return 0;
}

Measured memory_bytes: 1428
//Zory-2018
#include<cmath>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<map>
#include<set>
#include<queue>
#include<deque>
#include<bitset>
#include<vector>
#include<algorithm>
#include<iostream>
#include<stack>
using namespace std;

namespace mine
{
	const int MAX_N=2100;
	const int INF=0x3f3f3f3f;
	typedef long long ll;
	int mymax(int x,int y) {return x>y?x:y;}
	int mymin(int x,int y) {return x<y?x:y;}

	int p1[MAX_N*2];
	int f[MAX_N*2][MAX_N];
	int nw[MAX_N*2][MAX_N*2];
	void main()
	{
		int n;scanf("%d",&n);
		for(int i=1;i<=2*n;i++)
		{
			char s[5];int id;scanf("%s%d",s,&id);
			p1[id+n*(s[0]=='B')]=i;
		}

		for(int i=1;i<=2*n;i++)
			for(int t=1;t<=2*n;t++)
				nw[i][t]=nw[i][t-1]+(p1[t]>p1[i]);

		memset(f,63,sizeof f);f[0][0]=0;
		for(int x=1;x<=2*n;x++)
		{
			for(int a=0;a<=x and a<=n;a++)
			{
				int b=x-a;
				if(a>0) f[x][a]=mymin(f[x][a],
					f[x-1][a-1]+nw[a][a-1]+nw[a][n+b]-nw[a][n]
				);
				if(b>0) f[x][a]=mymin(f[x][a],
					f[x-1][a]+nw[n+b][a]+nw[n+b][n+b-1]-nw[n+b][n]
				);
			}
		}
		printf("%d",f[2*n][n]);
	}
};

int main()
{
	mine::main();
}


Measured memory_bytes: 103552
import sys
import math

from collections import defaultdict
from collections import deque
def load(vtype=int):
    return vtype(input().strip())
def load_list(seplator=" ", vtype=int):
    return [vtype(v) for v in input().strip().split(seplator)]
def exit():
    import sys
    sys.exit(0)
def perm_sub(li, used):
    if len(li) == len(used):
        return [deque()]
    k = []
    for i in range(len(li)):
        if i in used:
            continue
        used.add(i)
        sub_list = perm_sub(li, used)
        for sub in sub_list:
            sub.appendleft(li[i])
        k.extend(sub_list)
        used.discard(i)
    return k
def perm_li(li):
    return perm_sub(li, set())
def perm_n(n):
    return perm_sub(list(range(n)), set())
def join_i(li, sep=""):
    return sep.join([str(e) for e in li])
def li2n(li):
    n, base = 0, 1
    for i in range(len(li)-1, -1, -1):
        n += li[i] * base
        base *= 10
    return n
def sli2ili(li):
    return [int(s) for s in li] 
def prime_list(n):
    li = [i for i in range(2, n+1)]
    for i in range(len(li)):
        if li[i] >= int(math.sqrt(n)):
            break
        if li[i] == -1:
            continue
        for j in range(i+1, len(li)):
            if li[j] % li[i] == 0:
                li[j] = -1
    return [n for n in li if n != -1]
def gcd(a, b):
    a, b = max(a, b), min(a, b)
    while True:
        r = a % b
        if r == 0: return b
        a, b = b, r
def lcm(a, b):
    return int(a * b / gcd(a,b))
def all_subset(li):
    s = []
    n = len(li)
    for bit in range(0, (1<<(n+1))):
        ss = set()
        for i in range(0, n):
            if (bit & (1 << i)):
                ss.add(li[i])
        s.append(ss)
    return s
a = load()
b = load()

print(6-a-b)

Measured memory_bytes: 3316
#include<stdio.h>
int main(void)
{
	int n;
	char s[101];
	int i, cor, cob;

	cor = cob = 0;
	scanf("%d", &n);
	scanf("%s", s);
	for (i = 0; s[i] != '\0'; i++) {
		if (s[i] == 'R') {
			cor++;
		}
		else if(s[i] == 'B') {
			cob++;
		}
	}
	if (cor > cob) {
		printf("Yes\n");
	}
	else {
		printf("No\n");
	}
	return 0;
}

Measured memory_bytes: 128
#include <iostream>
#include <string>
using namespace std;
int main() {
    int a, b, c;
    cin >> a >> b;
    c = a;
    int cnt=1;
    if(b==1) {
        cout << '0' << endl;
        return 0;
    }
    while(c<b) {
        c += (a-1);
        cnt++;
    }
    cout << cnt << endl;
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <fstream>
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iomanip>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

#define EPS 1e-9
#define INF MOD
#define MOD 1000000007LL
#define fir first
#define iss istringstream
#define sst stringstream
#define ite iterator
#define ll long long
#define mp make_pair
#define rep(i,n) rep2(i,0,n)
#define rep2(i,m,n) for(int i=m;i<n;i++)
#define pi pair<int,int>
#define pb push_back
#define sec second
#define sh(i) (1LL<<i)
#define sz size()
#define vi vector<int>
#define vc vector
#define vl vector<ll>
#define vs vector<string>

ll n;

int main(){
	while(cin>>n&&n){
		string s;
		int f=0;
		while(n){
			if(f==0){
				int x=(n%10+10)%10;
				n-=x;
				s+='0'+x;
			}else{
				int x=(-n%10+10)%10;
				n+=x;
				s+='0'+x;
			}
			n/=10;
			f^=1;
		}
		reverse(s.begin(),s.end());
		cout<<s<<endl;
	}
}

Measured memory_bytes: 0
def binary_search(A, key, n):
    left = 0
    right = n
    while left < right:
        mid = int((left + right) / 2)
        if A[mid] == key:
            return True
        elif key < A[mid]:
            right = mid
        else:
            left = mid + 1
    return False

n = int(input())
S = list(map(int, input().split(" ")))
q = int(input())
T = list(map(int, input().split(" ")))

counter = 0
for t in T:
    if binary_search(S, t, n):
        counter += 1

print(counter)



Measured memory_bytes: 16712
#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b;
  cin >> a >> b;
  vector<int> vec(a);
  int ans = 0;
  for (int i = 0; i < a; i++) {
    cin >> vec[i];
    ans += min(vec[i], b - vec[i]);
  }
  cout << ans * 2 << endl;
}

Measured memory_bytes: 256
#include<iostream>
#include <algorithm>
#include<string>
#include <bitset>
#include <vector>
using namespace std;

int main()
{
	//int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, ans = 0;
	int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, ans = 0;
	//cout << LONG_MAX << endl;
	//string s[1001];

	cin >> a;
	cin >> b;
	for ( c = 1; c < b-a; c++)
	{
		d += c;
	}
	cout << d-a << endl;

	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define int long long
class UnionFind{
public:
  vector<int> par;
  UnionFind(int n){
    par = vector<int>(n,-1);
  }
  int root(int x){
    if(par[x]<0){return x;}
    else{return par[x]=root(par[x]);}
  }
  int size(int x){
    return -par[root(x)];  
  }
  void unite(int x, int y){
    x=root(x); y=root(y);
    if(x==y){return;}
    else{
      if(size(x)<size(y))swap(x,y);
      par[x]+=par[y];
      par[y]=x; return;
    }
  }
};
signed main(){
  int n,m; cin>>n>>m;
  UnionFind u(n);
  vector<int> ans(m,0); 
  vector<int> a(m),b(m);
  int i; 
  ans[m-1]= n*(n-1)/2;
  for(i=0;i<m;i++){cin>>a[i]>>b[i]; --a[i];--b[i];}
  for(i=m-1;i>=1;i--){
    ans[i-1]=ans[i];
    if(u.root(a[i])!=u.root(b[i])){
      ans[i-1]-= u.size(u.root(a[i]))*u.size(u.root(b[i]));
      u.unite(a[i],b[i]);
    }
  }
  for(i=0;i<m;i++){
    cout<<ans[i]<<endl;
  }
  return 0;
}


Measured memory_bytes: 4480
#include <bits/stdc++.h>
 
using namespace std;
 
typedef long long ll;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef pair<ll,ll> P;
typedef string str;
typedef vector<P> vp;
typedef vector<string> vs;
typedef vector<bool> vb;

const ll mod=1e9;
const ll inf=1e16;

#define rep(i,m,n) for(ll i=m;i<n;i++)
#define repr(i,m,n) for(ll i=m-1;i>=n;i--)
#define fi first
#define se second
#define chmax(x,y) x=max(x,y)
#define chmin(x,y) x=min(x,y)
#define eb(x) emplace_back(x)
#define pb(x) pop_back(x)
#define all(x) x.begin(),x.end()
#define allr(x) x.rbegin(),x.rend()
#define sum(x) accumulate(all(x),0)
#define pc(x) __builtin_popcount(x)
#define gll greater<ll>()

void solve(){
 ll n,k;
 cin >> n >> k;
 vll p(n),c(n);
  rep(i,0,n) {
    cin >> p[i]; 
    p[i]--;
    
  }
  rep(i,0,n) cin >> c[i];
  
  ll ans=-inf;
  rep(i,0,n){
    vll s;
    ll now=i;
    ll tot=0;
    while(1){
     tot+=c[p[now]];
     s.eb(tot); 
     now=p[now];
     if(now==i) break;
    }
    
    ll m=s.size();
    
    rep(j,0,m){
     if(j+1>k) break;
     ll loop=(k-j-1)/m;
     chmax(ans,s[j]+loop*max(tot,0ll));
      
    }
    
  }
  cout << ans << endl;
  
  
 
}
int main(){
   cin.tie(nullptr);
  ios::sync_with_stdio(false);
  solve();
}


Measured memory_bytes: 3772
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>

using namespace std;
constexpr int MAX_LOG_V = 50;
template<class T> inline bool chmax(T &a, T b){ if(a < b){a = b; return true;} return false;}

struct Edge{
    int to,weight;
    Edge(int t,int w) : to(t), weight(w){}
};

using Edges = vector<Edge>;
using Graph = vector<Edges>;

class Tree{
    public:
        Tree(int size) : mGraph(size), mMemo(size) {}
        void add_edge(int s, int t, int w = 1){
            mGraph[s].emplace_back(t,w);
            mGraph[t].emplace_back(s,w);
        }

        void SetParentAndDepth(int v,int pv, int d){
            mPar[0][v] = pv; // v is pv's 2^0 parent
            mDepth[v] = d;
            for(auto nv : mGraph[v]){
                if(nv.to == pv) continue;
                SetParentAndDepth(nv.to,v,d+1);
            }
        }

        void Init(int root){
            mPar.resize(MAX_LOG_V,vector<int>(mGraph.size()));
            mDepth.resize(mGraph.size());
            SetParentAndDepth(root,-1,0);
            // calc 2^k parent of each vert
            for(int k = 0; k + 1 < MAX_LOG_V; ++k){
                for(int v = 0; v < mGraph.size(); ++v){
                    if(mPar[k][v] < 0) mPar[k+1][v] = -1; // not having parent
                    else mPar[k+1][v] = mPar[k][mPar[k][v]];
                }
            }
        }

        vector<int> GetDepth(){return mDepth;}


    private:
        Graph mGraph;
        Graph mMemo;
        
        // LCA
        vector<vector<int> > mPar;
        vector<int> mDepth;
};

int main(){
    int n,q,k,x,y;
    cin >> n;
    Tree tree(n);
    for(int i = 0; i < n-1; ++i){
        cin >> x >> y;
        --x;--y;
        tree.add_edge(x,y);
    }
    tree.Init(0);
    vector<int> c(n);
    for(int i = 0; i < n; ++i) cin >> c[i];
    sort(c.begin(),c.end(),greater<int>());

    auto depth = tree.GetDepth();
    vector<pair<int,int> > ans;
    for(int i = 0; i < depth.size();++i){
        ans.emplace_back(depth[i],i);
    }
    sort(ans.begin(),ans.end());
    int aa = 0;
    vector<pair<int,int> > aaa;
    for(int i = 0; i <ans.size();++i){
        aaa.emplace_back(ans[i].second,c[i]);
        if(i!=0) aa += c[i];
    }
    cout << aa << endl;
    sort(aaa.begin(),aaa.end());
    for(int i = 0; i < aaa.size(); ++i){
        cout << aaa[i].second << (i==aaa.size()-1 ? '\n' : ' ');
    }
    return 0;
}

Measured memory_bytes: 3708
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int mod = 1e9 + 7;
const int inf = (1 << 30) - 1;
const ll infll = (1LL << 61) - 1;

string s;

int main()
{
    cin >> s;
    sort(s.begin(), s.end());
    if (s[0] == s[1] && s[2] == s[3] && s[1] != s[2])
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}


Measured memory_bytes: 256
#!/usr/bin/env python
# coding: utf-8

from collections import namedtuple
from heapq import *


class Elem:
    def __init__(self, v, a, b, c):
        self.v = v
        self.a = a
        self.b = b
        self.c = c

    def __lt__(self, other):
        return self.v > other.v

    def __str__(self):
        return "{} {} {} {}".format(self.v, self.a, self.b, self.c)

    def __repr__(self):
        return self.__str__()

    def id(self):
        return self.a*1000*1000+self.b*1000+self.c

X, Y, Z, K = list(map(int, input().split()))
la = list(map(int, input().split()))
lb = list(map(int, input().split()))
lc = list(map(int, input().split()))
la.sort(reverse=True)
lb.sort(reverse=True)
lc.sort(reverse=True)
ids = set()

def next(e):
    elems = []
    if e.a < len(la)-1:
        elems.append(Elem(la[e.a+1]+lb[e.b]+lc[e.c],e.a+1,e.b,e.c))
    if e.b < len(lb)-1:
        elems.append(Elem(la[e.a]+lb[e.b+1]+lc[e.c],e.a,e.b+1,e.c))
    if e.c < len(lc)-1:
        elems.append(Elem(la[e.a]+lb[e.b]+lc[e.c+1],e.a,e.b,e.c+1))
    return elems

def main():
    best = Elem(la[0]+lb[0]+lc[0], 0, 0, 0)
    h = []
    heappush(h, best)
    cnt = 0
    while True:
        if len(h) == 0:
            break
        e = heappop(h)
        if e.id() in ids:
            continue
        ids.add(e.id())
        elems = next(e)
        for ne in elems:
            heappush(h, ne)
        print(e.v)
        cnt += 1
        if cnt == K:
            break


if __name__ == '__main__':
    main()


Measured memory_bytes: 5484
N = int(input())
abc = [list(map(int, input().split())) for i in range(N)]

dp = [[abc[0][0], abc[0][1], abc[0][2]]] + [[0, 0, 0] for i in range(N - 1)]

for i in range(1, N):
    dp[i][0] = abc[i][0] + max(dp[i - 1][1], dp[i - 1][2])
    dp[i][1] = abc[i][1] + max(dp[i - 1][0], dp[i - 1][2])
    dp[i][2] = abc[i][2] + max(dp[i - 1][0], dp[i - 1][1])
print(max(dp[N - 1][0], dp[N - 1][1], dp[N - 1][2]))


Measured memory_bytes: 105304
#include <bits/stdc++.h>
using namespace std;
int tile_reverse(string A, char flag)
{
    int ans = 0;
    char tmp_flag = flag;
    if (A[0] != tmp_flag)
    {
        ans++;
    }
    for (int i = 1; i < A.size(); i++)
    {
        if (A[i] == tmp_flag)
        {
            ans++;
            if (A[i] == '0')
            {
                tmp_flag = '1';
            }
            else
            {
                tmp_flag = '0';
            }
        }
        else
        {
            tmp_flag = A[i];
        }
    }
    return ans;
}
int main()
{
    string S;
    cin >> S;
    int ans0, ans1;
    ans0 = tile_reverse(S, '0');
    ans1 = tile_reverse(S, '1');
    cout << min(ans0, ans1) << endl;
    return 0;
}

Measured memory_bytes: 512