akhauriyash/Code-Regression huggingface dataset:
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0203

"""
import sys
from sys import stdin
from collections import deque, defaultdict
input = stdin.readline


def solve(field):
    BLANK, OBSTACLE, JUMP = 0, 1, 2
    ans = 0                     #  ??????????????°???????????°

    dy = [1, 1, 1]  # ?????????????????????????????????????§???????
    dx = [0, -1, 1]
    x_limit = len(field[0])
    y_limit = len(field)

    path = defaultdict(int)     #  ??????????????????????????°???????????°????????????'x???_y???'???????????????
    Q = deque()
    for x, m in enumerate(field[0]):
        if m == BLANK:              #  ?????????????????°?????´?????????????????????????????????
            t = '{}_{}'.format(x, 0)
            Q.append((x, 0))
            path[t] = 1

    while Q:
        cx, cy = Q.popleft()        #  ?????¨??°?????§?¨?
        t = '{}_{}'.format(cx, cy)
        num = path.pop(t)

        if field[cy][cx] == OBSTACLE:
            continue
        elif field[cy][cx] == JUMP: #  ?????£????????§?????°?????????????????£????????°
            if cy+2 > y_limit-1:
                ans += num
            else:
                t = '{}_{}'.format(cx, cy+2)
                if not path[t]:
                    Q.append((cx, cy+2))
                path[t] += num
            continue
        elif cy == y_limit -1:
            ans += num
            continue

        for i in range(3):      #  ?????????3???len(dy)?????????
            nx = cx + dx[i]     #  ?????°????????§?¨?
            ny = cy + dy[i]

            if 0<= nx < x_limit:
                if field[ny][nx] == JUMP and dx[i] == 0: #  ?????£????????°????????£??????????????\????????´???
                    if ny+2 > y_limit - 1:
                        ans += num
                    else:
                        t = '{}_{}'.format(nx, ny+2)
                        if not path[t]:
                            Q.append((nx, ny+2))
                        path[t] += num
                elif field[ny][nx] == BLANK:
                    if (ny >= y_limit - 1):
                        ans += num
                    else:
                        t = '{}_{}'.format(nx, ny)
                        if not path[t]:
                            Q.append((nx, ny))
                        path[t] += num
    return ans


def main(args):
    while True:
        X, Y = map(int, input().strip().split())
        if X == 0 and Y == 0:
            break
        field = []
        for _ in range(Y):
            temp = [int(x) for x in input().strip().split()]
            field.append(temp)
        result = solve(field)
        print(result)


if __name__ == '__main__':
    main(sys.argv[1:])

Measured memory_bytes: 8080
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int mod=1000000007;
int N,K;
vector<vector<int>> operator*(vector<vector<int>> A,vector<vector<int>> B){
  vector<vector<int>> C(N,vector<int>(N,0));
  for(int i=0;i<N;i++)
    for(int j=0;j<N;j++)
      for(int k=0;k<N;k++)
        C[i][j]=(C[i][j]+A[i][k]*B[k][j]%mod)%mod;
  return C;
}
vector<vector<int>> p(vector<vector<int>> A,int B){
  if(!B){
    vector<vector<int>> C(N,vector<int>(N,0));
    for(int i=0;i<N;i++)C[i][i]=1;
    return C;
  }
  if(B%2)return p(A,B-1)*A;
  vector<vector<int>> C=p(A,B/2);
  return C*C;
}
signed main(){
  cin>>N>>K;
  vector<vector<int>> A(N,vector<int>(N));
  for(int i=0;i<N;i++)
    for(int j=0;j<N;j++)cin>>A[i][j];
  vector<vector<int>> B=p(A,K);
  int ans=0;
  for(int i=0;i<N;i++)
    for(int j=0;j<N;j++)ans=(ans+B[i][j])%mod;
  cout<<ans<<endl;
}

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

const int MOD = (int)1e9+7;

int main(){
	int N;
	cin >> N;
	vector<int> d(N);
	for(int i=0;i<N;i++)	cin >> d.at(i);

	sort(d.begin(),d.end());
	if(d.at(N/2)-d.at(N/2-1)==0)	cout << 0 << endl;
	else	cout << d.at(N/2)-d.at(N/2-1) << endl;

	return 0;
}


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

typedef long long ll;

int main() {
    while(true) {
        int n, m, a;
        cin >> n >> m >> a;
        if(n == 0 && m == 0 &&a == 0) break;
        vector<int> members;
        vector<vector<int>> bars;
        for(int i = 0; i < n; i++) {
            members.push_back(i);
        }
        for (int i = 0; i < m; i++) {
            int h, p, q; cin >> h >> p >> q;
            p--; q--;
            bars.push_back({h, p, q});
            sort(bars.begin(), bars.end());
        }
        for (int i = 0; i < m; i++) {
            int temp = members[bars[i][1]];
            members[bars[i][1]] = members[bars[i][2]];
            members[bars[i][2]] = temp;
        }
        cout << members[a-1] + 1<< endl;
    }

}


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


void solve(long long A, long long B){
    printf("%lld", max({A+B, A-B, A*B})) ;
}

// Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
int main(){
    long long A;
    scanf("%lld",&A);
    long long B;
    scanf("%lld",&B);
    solve(A, B);
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long LL;
#define INF 0x3f3f3f3f;
LL h, w, ans, s1, s2, s3;
int main()
{
    scanf("%I64d%I64d",&h,&w);
    if(h>w)swap(h,w);
    if(h%3==0||w%3==0)printf("0\n");
    else
    {
        ans=INF;
        for(int i=1;i<=w/2+1;i++)   //三分h
        {
            s1=h*i;
            s2=h*((w-i)/2);
            s3=h*((w-i)-(w-i)/2);
            ans=min(ans,max(s1,max(s2,s3))-min(s1,min(s2,s3)));
        }
        for(int i=1;i<=h/2+1;i++)
        {
            s1=w*i;
            s2=(h-i)*(w/2);
            s3=(h-i)*(w-w/2);
            ans=min(ans,max(s1,max(s2,s3))-min(s1,min(s2,s3)));
        }
        for(int i=1;i<=w/2+1;i++)
        {
            s1=h*i;
            s2=(h/2)*(w-i);
            s3=(h-h/2)*(w-i);
            ans=min(ans,max(s1,max(s2,s3))-min(s1,min(s2,s3)));
        }
        printf("%I64d\n",ans);
    }
    return 0;
}


Measured memory_bytes: 256
n, k = map(int, input().split())

if k == 0:
    print(n * n)
    exit()

ans = 0
for i in range(k+1, n+1):
    quo, rem = divmod(n, i)
    ans += quo * (i-k)
    if rem >= k:
        ans += rem - k + 1

print(ans)

Measured memory_bytes: 65436
let () =
  let idx = [0; 1; 2; 3] in
  let rec f () =
    try
      let s = read_line() in
      let ax = Scanf.sscanf s "%d %d %d %d" (fun a b c d -> [a; b; c; d]) in
      let s = read_line() in
      let bx = Scanf.sscanf s "%d %d %d %d" (fun a b c d -> [a; b; c; d]) in
      let g (h, b) vb i =
        let gg (h, b) va j =
          if va = vb then
            if i = j then (h+1, b) else (h, b+1)
          else
            (h, b)
        in
        let (h, b) = List.fold_left2 gg (h, b) ax idx in
        (h, b)
      in
      let (h, b) = List.fold_left2 g (0, 0) bx idx in
      Printf.printf "%d %d\n" h b;
      f ()
    with
    | End_of_file -> ()
  in
  f ()

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

int main()
{
  string S;
  cin >> S;
  ll len = S.size();

  reverse(S.begin(), S.end());
  vector<vector<ll>> dp(len+1, vector<ll>(13, 0));
  dp[0][0]=1;
  int mul = 1;
  for (int i=0; i<len; i++) {
    int c = -1;
    if (S[i] != '?') c = S[i]-'0';

    for (int j=0; j<=9; j++) {
      if (c!=-1 && c!=j) continue;
      for (int k=0; k<13; k++) {
        dp[i+1][(mul*j+k)%13] += dp[i][k];
      }
    }
    for (int j=0; j<13; j++) {
      dp[i+1][j] %= mod;
    }
    mul *= 10;
    mul %= 13;
  }
  cout << dp[len][5] << endl;

  return 0;
}


Measured memory_bytes: 13696
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define x first
#define y second
#define pii pair<int,int>
#define pb push_back
#define eb emplace_back
#pragma GCC optimize("unroll-loops")

using namespace std;
using namespace __gnu_pbds;

typedef long long int ll;
typedef unsigned long long int ull;
int MOD=1000000007;
int MOD2=998244353;
vector<int> bases;
const ll LLINF=1ll<<60;
const char en='\n';

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
void yes() {cout<<"YES"<<en; exit(0);}
void no() {cout<<"NO"<<en; exit(0);}
inline int rund() {int x576363482791fuweh=rng();return abs(x576363482791fuweh)%RAND_MAX;}
template<class T>
void prVec(vector<T> w)
{
	cout<<w.size()<<endl;
	for (int i=0;i<int(w.size())-1;++i) cout<<w[i]<<' ';
	if (w.size()) cout<<w[w.size()-1]<<endl;
}

void M998()
{
	swap(MOD,MOD2);
}

ll raand()
{
	ll a=rund();
	a*=RAND_MAX;
	a+=rund();
    return a;
}

#define rand raand

ll raaand()
{
	return raand()*(MOD-7)+raand();
}

string to_upper(string a)
{
	for (int i=0;i<(int)a.size();++i) if (a[i]>='a' && a[i]<='z') a[i]-='a'-'A';
	return a;
}

string to_lower(string a)
{
	for (int i=0;i<(int)a.size();++i) if (a[i]>='A' && a[i]<='Z') a[i]+='a'-'A';
	return a;
}

ll sti(string a)
{
	ll k=0;
	for (int i=0;i<(int)a.size();++i)
	{
		k*=10;
		k+=a[i]-'0';
	}
	return k;
}

string its(ll k)
{
	if (k==0) return "0";
	string a;
	while (k)
	{
		a.push_back((k%10)+'0');
		k/=10;
	}
	reverse(a.begin(),a.end());
	return a;
}

ll min(ll a,int b)
{
	if (a<b) return a;
	return b;
}

ll min(int a,ll b)
{
	if (a<b) return a;
	return b;
}

ll max(ll a,int b)
{
	if (a>b) return a;
	return b;
}

ll max(int a,ll b)
{
	if (a>b) return a;
	return b;
}

ll gcd(ll a,ll b)
{
	if (b==0) return a;
	return gcd(b,a%b);
}

ll lcm(ll a,ll b)
{
	return a/gcd(a,b)*b;
}

template<class T,class K>
pair<T,K> mp(T a,K b)
{
	return make_pair(a,b);
}

inline int mult(ll a,ll b)
{
	return (a*b)%MOD;
}

inline int pot(int n,int k)
{
	if (k==0) return 1;
	ll a=pot(n,k/2);
	a=mult(a,a);
	if (k%2) return mult(a,n);
	else return a;
}

int divide(int a,int b)
{
	return mult(a,pot(b,MOD-2));
}

inline int sub(int a,int b)
{
	if (a-b>=0) return a-b;
	return a-b+MOD;
}

inline int add(int a,int b)
{
	if (a+b>=MOD) return a+b-MOD;
	return a+b;
}

bool prime(ll a)
{
	if (a==1) return 0;
	for (int i=2;i<=round(sqrt(a));++i)
	{
		if (a%i==0) return 0;
	}
	return 1;
}

ll has(string x)
{
	ll h1=0,h2=0;
	x=to_lower(x);
	for (char a: x)
	{
		h1*=bases[0];
		h1+=a-'a';
		h1%=bases[3];
		h2*=bases[1];
		h2+=a-'a';
		h2%=bases[4];
	}
	return h1*(MOD+13893829)+h2;
}

const int N=300010;
int n;
vector<int> a;
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	for (int i=0;i<10;++i) bases.push_back(rand()%(MOD-13893829)+13893829);
	cin>>n;
	while (n--)
	{
		int x;
		cin>>x;
		x=MOD-x;
		auto it=upper_bound(a.begin(),a.end(),x);
		if (it==a.end()) a.pb(x);
		else *it=x;
	}
	cout<<a.size();
}


Measured memory_bytes: 892
#include <iostream>

using namespace std;

int n , s;

int dfs(int i , int sum , int N){

	if(N == 0 && sum == 0) return 1;//yes
	if(N == 0 || i == 10) return 0;//no

	return dfs(i + 1 , sum , N) + dfs(i + 1 , sum - i , N - 1);
}

int main(){

	while(1){
		cin >> n >> s;
		if(n == 0 && s == 0) break;

		cout << dfs(0 , s , n) << endl;
	}
	return 0;
}

Measured memory_bytes: 3088
use std::io;
use std::f64; // cf. https://stackoverflow.com/questions/31208465/pi-constant-is-ambiguous
use std::ops;

fn main() {
    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read_line");
    let depth: i32 = input.trim().parse().expect("Failed to parse");
    let mut pts = Vec::<Vec2>::new(); // TODO: reserveする
    calc_koch(
        depth,
        &Vec2::new(0.0, 0.0),
        &Vec2::new(100.0, 0.0),
        &mut pts,
    );
    for v in pts {
        println!("{} {}", v.x, v.y);
    }
}

fn calc_koch(n: i32, pt_0: &Vec2, pt_1: &Vec2, out_vec: &mut Vec<Vec2>) {
    calc_koch_sub(n, pt_0, pt_1, out_vec);
    out_vec.push(Vec2::copy(pt_1));
}

fn calc_koch_sub(n: i32, pt_0: &Vec2, pt_1: &Vec2, out_vec: &mut Vec<Vec2>) {
    if n == 0 {
        out_vec.push(Vec2::copy(pt_0));
    } else {
        let pt_a = &(pt_0 * (2.0 / 3.0)) + &(pt_1 * (1.0 / 3.0));
        let pt_c = &(pt_0 * (1.0 / 3.0)) + &(pt_1 * (2.0 / 3.0));
        let pt_b = pt_0
            + &(&(&Mat2::rotate(f64::consts::PI / 6.0) * &(pt_1 - pt_0)) * (1.0 / f64::sqrt(3.0)));
        calc_koch_sub(n - 1, &pt_0, &pt_a, out_vec);
        calc_koch_sub(n - 1, &pt_a, &pt_b, out_vec);
        calc_koch_sub(n - 1, &pt_b, &pt_c, out_vec);
        calc_koch_sub(n - 1, &pt_c, &pt_1, out_vec);
    }
}

struct Vec2 {
    x: f64,
    y: f64,
}

impl Vec2 {
    fn new(x: f64, y: f64) -> Vec2 {
        Vec2 { x: x, y: y }
    }
    fn copy(src: &Vec2) -> Vec2 {
        Vec2 { x: src.x, y: src.y }
    }
}

// cf. https://stackoverflow.com/questions/28005134/how-do-i-implement-the-add-trait-for-a-reference-to-a-struct

impl<'a, 'b> ops::Add<&'b Vec2> for &'a Vec2 {
    type Output = Vec2;

    fn add(self, rhs: &'b Vec2) -> Vec2 {
        Vec2 {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl<'a, 'b> ops::Sub<&'b Vec2> for &'a Vec2 {
    type Output = Vec2;

    fn sub(self, rhs: &'b Vec2) -> Vec2 {
        Vec2 {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

impl<'a> ops::Mul<f64> for &'a Vec2 {
    type Output = Vec2;

    fn mul(self, rhs: f64) -> Vec2 {
        Vec2 {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

struct Mat2 {
    a: f64,
    b: f64,
    c: f64,
    d: f64,
}

impl Mat2 {
    fn new(a: f64, b: f64, c: f64, d: f64) -> Mat2 {
        Mat2 {
            a: a,
            b: b,
            c: c,
            d: d,
        }
    }

    fn rotate(t: f64) -> Mat2 {
        Mat2::new(f64::cos(t), -f64::sin(t), f64::sin(t), f64::cos(t))
    }
}

impl<'a, 'b> ops::Mul<&'b Vec2> for &'a Mat2 {
    type Output = Vec2;

    fn mul(self, rhs: &'b Vec2) -> Vec2 {
        Vec2 {
            x: self.a * rhs.x + self.b * rhs.y,
            y: self.c * rhs.x + self.d * rhs.y,
        }
    }
}



Measured memory_bytes: 5060
N,L=map(int, input().split())
sum=0

if L>=1:
  for i in range(1,N):
    sum=sum+(L+i)
else:
  if N>-1*L:
    for i in range(0,N):
      sum=sum+(L+i)
  else:
    for i in range(0,N-1):
      sum=sum+(L+i)

print(sum)
    
    
    


Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;
#define fl(i,a,b) for(int i=a;i<b;i++)
#define ll long long
#define endl '\n'
#define pb push_back
#define ff first
#define ss second
#define mod 1000000007
#define mx 100001
#define inf 2e9
#define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
int main()
{
	fast;
	int n;
	cin>>n;
	int h[n+1]={0};
	for(int i=0;i<n;i++)
		cin>>h[i];
	std::vector<int> dp(n,inf);
	dp[0]=0;
	for(int i=0;i<n;i++)
    {
        for(int j=i+1;j<=i+2;j++)
        {
            if(j<n)
                dp[j]=min(dp[j],dp[i]+abs(h[j]-h[i]));
        }
    }
    cout<<dp[n-1]<<endl;;
}


Measured memory_bytes: 1152
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cctype>
 
#include <algorithm>
#include <tuple>
#include <random>
#include <bitset>
#include <queue>
#include <functional>
#include <set>
#include <map>
#include <vector>
#include <chrono>
#include <iostream>
#include <limits>
#include <numeric>
 
#define LOG(FMT...) fprintf(stderr, FMT)

using namespace std;

typedef long long ll;
typedef unsigned long long ull;

// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
 
template <class T>
istream& operator>>(istream& is, vector<T>& v) {
  for (T& x : v)
    is >> x;
  return is;
}
 
template <class T>
ostream& operator<<(ostream& os, const vector<T>& v) {
  if (!v.empty()) {
    os << v.front();
    for (int i = 1; i < v.size(); ++i)
      os << ' ' << v[i];
  }
  return os;
}

const int N = 100010;

int prt[N], sub[N];
ll d[N], sum[N];

void gg() {
  cout << "-1\n";
  exit(0);
}

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

  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i)
    cin >> d[i];
  map<ll, int, greater<ll>> mp;
  for (int i = 1; i <= n; ++i)
    mp.insert(make_pair(d[i], i));
  fill(sub + 1, sub + n + 1, 1);
  for (int rep = 1; rep < n; ++rep) {
    int u = mp.begin()->second;
    mp.erase(mp.begin());
    ll goal = d[u] - (n - 2 * sub[u]);
    auto it = mp.find(goal);
    if (it == mp.end())
      gg();
    prt[u] = it->second;
    sub[it->second] += sub[u];
    sum[it->second] += sum[u] + sub[u];
  }
  int rt = mp.begin()->second;
  if (sum[rt] != d[rt])
    gg();
  for (int i = 1; i <= n; ++i)
    if (i != rt)
      cout << i << ' ' << prt[i] << '\n';

  return 0;
}


Measured memory_bytes: 9984
#include<stdio.h>
int main()
{
    int k,s,x,y,z,count=0;
    scanf("%d %d",&k,&s);
    for(x=0;x<=k;x++)
    {
        for(y=0;y<=k;y++)
        {
            z=s-x-y;
            if(z<=k && z>=0)
            {
                count++;
            }
        }
    }
    printf("%d\n",count);

    return 0;
}


Measured memory_bytes: 128
import java.util.Scanner;

public class Main {
	public static class Vertex {
		int     digree;
		Vertex  neighbor[];
		int     cost[];
		int     minCost;
		boolean flag;
		int label;

		Vertex(int n, int k) {
			digree = 0;
			neighbor = new Vertex[n];
			cost = new int[n];
			minCost = Integer.MAX_VALUE;
			flag = false;
			label = k;
		}
	}

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int n, k;
		int order;
		Vertex v[];

		n = sc.nextInt();
		k = sc.nextInt();
		while (n + k != 0) {
			v = new Vertex[n];
			for (int i = 0; i < n; i++) {
				v[i] = new Vertex(n, i);
			}

			for (int i = 0; i < k; i++) {
				order = sc.nextInt();
				if (order == 1) {
					int v1 = sc.nextInt() - 1;
					int v2 = sc.nextInt() - 1;
					int cost = sc.nextInt();
					boolean flag = true;

					for (int j = 0; j < v[v1].digree && flag; j++) {
						if (v[v1].neighbor[j] == v[v2]) {
							v[v1].cost[j] = (cost < v[v1].cost[j]) ? cost : v[v1].cost[j];
							flag = false;
						}
					}
					for (int j = 0; j < v[v2].digree && !flag; j++) {
						if (v[v2].neighbor[j] == v[v1]) {
							v[v2].cost[j] = (cost < v[v2].cost[j]) ? cost : v[v2].cost[j];
						}
					}
					if (flag) {
						v[v1].neighbor[v[v1].digree] = v[v2];
						v[v1].cost[v[v1].digree++] = cost;
						v[v2].neighbor[v[v2].digree] = v[v1];
						v[v2].cost[v[v2].digree++] = cost;
					}
				} else if (order == 0) {
					int v1 = sc.nextInt() - 1;
					int v2 = sc.nextInt() - 1;
					System.out.println(dijkstra(v, n, v1, v2));
				}
			}
			n = sc.nextInt();
			k = sc.nextInt();
		}
	}

	public static int dijkstra(Vertex v[], int n, int start, int goal) {
		boolean flag = true;

		for (int i = 0; i < n; i++) {
			v[i].flag = false;
			v[i].minCost = Integer.MAX_VALUE;
		}
		v[start].minCost = 0;
		v[start].flag = true;

		while (!v[goal].flag) {
			flag = false;
			int minIndex  = -1;
			for (int i = 0; i < n; i++) {
				if (v[i].flag) {
					for (int j = 0; j < v[i].digree; j++) {
						if (!v[i].neighbor[j].flag) {
							if (v[i].minCost + v[i].cost[j] < v[i].neighbor[j].minCost) {
								v[i].neighbor[j].minCost = v[i].minCost + v[i].cost[j];
							}
							if (minIndex == -1) {
								minIndex  = v[i].neighbor[j].label;
							} else if (v[i].neighbor[j].minCost < v[minIndex].minCost) {
								minIndex  = v[i].neighbor[j].label;
							}
						}
					}
				}
			}
			if (minIndex != -1) {
				v[minIndex].flag = true;
				flag = true;
			}
			if (!flag) {
				return -1;
			}
		}
		return v[goal].minCost;
	}
}

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

using namespace std;

#define COUNTOF(array) (sizeof(array) / sizeof(array[0]))
#define OUT(P) cout << (P) << endl
#define OUT2(P1, P2) cout << (P1) << " " << (P2) << endl
#define PRINT_ARRAY(P) for(int i=0; i<P.size(); i++) cout << P[i] << endl;
#define PRINT_ARRAY_INLINE(P) do { for(int i=0; i<P.size(); i++) cout << P[i] << " "; cout << endl; } while(0)
#define PRINT_ARRAY_WITH_LABEL(L, P) do { cout << L << ": "; PRINT_ARRAY_INLINE(P); cout << endl; } while(0)
typedef long long ll;

int sum_digits(int num);
template <class T>
vector<T> copy_vector(vector<T> vec);
int gcd(int a, int b);



int digits_to_num(string digits) {
    int rtn = 0;
    int digits_size = digits.size();
    for(int i=0; i<digits_size; i++) {
        if(digits[i] == '1') {
            rtn += pow(-2, (digits_size - i - 1));
        }
    }
    return rtn;
}
string dfs(int n, string digits) {
    // 0, 1, -1の3パターンがある
    if(n == 1) {
        return '1' + digits;
    } else if(n % (-2) == 0) {
        return dfs(n / (-2), '0' + digits);
    } else if(n % (-2) == 1) {
        return dfs(n / (-2), '1' + digits);
    } else { // -1のとき
        // ここでは-2^n乗を用意しといて次の桁に持ち越して計算させることにする
        return dfs(n / (-2) + 1, '1' + digits);
    }
}


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

    if(n == 0) {
        cout << "0" << endl;
    } else {
        cout << dfs(n, "") << endl;
    }

    return 0;
}

/******************************/
/***** DECRARED FUNCTIONS *****/
/******************************/

int sum_digits(int num) {
    int rtn = 0;
    while(num != 0) {
        int tmp = num % 10; 
        rtn += tmp;
        num /= 10; 
    }   
    return rtn;
}
//int sum_digits(int num) {
//    int rtn = 0;
//    string num_str = to_string(num);
//    for(int i=0; i<num_str.size(); i++) {
//        rtn += num_str[i] - '0';
//    }   
//    return rtn;
//}

// vectorのコピー
template <class T>
vector<T> copy_vector(vector<T> vec) {
    vector<T> rtn;
    rtn.reserve(vec.size());
    copy(vec.begin(), vec.end(), back_inserter(rtn));
    return rtn;
}

// ユークリウッドの互除法
int gcd(int a, int b) {
    if(b==0) return a;
    else return gcd(b, a % b);
}



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

int main()
{
int H,W,ans=0;scanf("%d %d",&H,&W);
vector<vector<int>> c(10,vector<int>(10));vector<vector<int>> A(H,vector<int>(W));
for(int i=0;i<10;i++)for(int j=0;j<10;j++)scanf("%d",&c[i][j]);
for(int i=0;i<10;i++)c[i][i]=0;
for(int k=0;k<10;k++)for(int i=0;i<10;i++)for(int j=0;j<10;j++)
{
  c[i][j]=min(c[i][j],c[i][k]+c[k][j]);
}
for(int i=0;i<H;i++)for(int j=0;j<W;j++)
{
  scanf("%d",&A[i][j]);
  if(A[i][j]==-1)continue;
  ans+=c[A[i][j]][1];
}
printf("%d\n",ans);
}

Measured memory_bytes: 384
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e6+1000;
const ll mod=1e9+7;

ll fac[N],inv[N];
ll fast(ll x,ll n) {
    ll ans=1;
    for(;n;n>>=1,x=x*x%mod)
        if(n&1) ans=ans*x%mod;
    return ans;
}
void init(){
    inv[0]=inv[1]=1;
    for(int i=2;i<=N;i++)
        inv[i]=(mod-mod/i)*inv[mod%i]%mod;
}
ll C(ll n,ll m) {
    ll ans=n*inv[1]%mod;
    for(int i=2;i<=m;i++) {
        ans=ans*inv[i]%mod*(n-i+1)%mod;
    }
    return ans;
}

int main() {
    init();
    ll n,a,b;cin>>n>>a>>b;
    ll ans=(fast(2,n)-1+mod)%mod;
    ans=(ans-C(n,a)+mod)%mod;
    ans=(ans-C(n,b)+mod)%mod;
    cout<<ans;
}


Measured memory_bytes: 8448
#include<bits/stdc++.h>
#define ll long long
#define N 200010
#define mid ((l+r)>>1)
#define ls a[t].l
#define rs a[t].r
using namespace std;
struct dat{int c,l,r;} e[N];
struct segt
{
	dat a[N*80];int cnt=1;
	void psd(int t)
	{
		if (!ls) ls=++cnt;if (!rs) rs=++cnt;if (!a[t].c) return;
		a[ls].c=a[rs].c=a[t].c;a[t].c=0;
	}
	void upd(int t,int l,int r,int x,int y,int k)
	{
		if (x<=l && r<=y) {a[t].c=k;return;}psd(t);
		if (x<=mid) upd(ls,l,mid,x,y,k);if (y>mid) upd(rs,mid+1,r,x,y,k);
	}
	int qry(int t,int l,int r,int x)
	{
		while (l<r) {psd(t);if (x<=mid) t=ls,r=mid;else l=mid+1,t=rs;}return a[t].c;
	}
}sgt;
bool cmp(dat a,dat b){return a.c>b.c;}
int main()
{
	int n,q,i;cin>>n>>q;sgt.upd(1,0,1e9,0,1e9,-1);
	for (i=1;i<=n;i++) scanf("%d%d%d",&e[i].l,&e[i].r,&e[i].c),e[i].l-=e[i].c,e[i].r-=e[i].c+1;
	sort(e+1,e+n+1,cmp);for (i=1;i<=n;i++) sgt.upd(1,0,1e9,max(e[i].l,0),max(e[i].r,0),e[i].c);
	while (q--)
	{
		scanf("%d",&i);printf("%d\n",sgt.qry(1,0,1e9,i));
	}
}


Measured memory_bytes: 150144
import sys
sys.setrecursionlimit(1000000)

n,m=map(int,input().split())
e=[]
tu=[[] for x in range(n+1)]
d=[0]*(n+1)
fa=[0]*(n+1)
for i in range(n-1+m):
    u,v=map(int,input().split())
    e.append((u,v))
    tu[u].append(v)
    d[v]+=1

def dfs(x):
    if x in vis:
        return
    vis.add(x)
    for t in tu[x]:
        dfs(t)
    tp.append(x)

vis=set()
tp=[]
for i in range(1,n+1):
    if d[i]==0:
      dfs(i)

d=[0]*(n+1)
tp.reverse()
for i in tp:
    for t in tu[i]:
        d[t]=max(d[t],d[i]+1)

for i in e:
    u,v=i
    if d[u]+1==d[v]:
        fa[v]=u

for i in range(1,n+1):
    print(fa[i])


Measured memory_bytes: 116708
import sys

sys.setrecursionlimit(4100000)


def inputs(num_of_input):
    ins = [input() for i in range(num_of_input)]
    return ins


def solve(inputs):
    [K, X] = string_to_int(inputs[0])
    ret = []
    for i in range(X - K + 1, X + K):
        if i >= -1000000 and i <= 1000000:
            ret.append(i)
    return ret


def string_to_int(string):
    return list(map(lambda x: int(x), string.split()))


if __name__ == "__main__":
    ret = solve(inputs(1))
    s = ""
    for i in ret:
        s += "{} ".format(i)
    print(s.strip())


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

using namespace std;
using ll = long long;

int main() {

	ll N, A, B;
	cin>>A>>B;
	for (int x = 1;x <= 1250;++x) {
		if (int(x * 0.08) == A && int(x * 0.1) == B) {
			cout<<x<<endl;
			return 0;
		}
	}

	cout<<-1<<endl;
	return 0;
}


Measured memory_bytes: 256
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    k, t = map(int, readline().split())
    a = list(map(int, readline().split()))
    ans = 0
    prev = -1

    for _ in range(k):
        max_a = 0
        cur = -1
        for i in range(t):
            if i != prev:
                if a[i] > max_a:
                    max_a = a[i]
                    cur = i
        if cur != -1:
            a[cur] -= 1
            prev = cur

    print(sum(a))


if __name__ == '__main__':
    main()


Measured memory_bytes: 66980
N = int(input())
W = [input() for _ in range(N)]
used = []
ans = "Yes"

used.append(W[0])

for x in range(N-1):
    if W[x][-1] != W[x+1][0]:
        #print(W[x][0])
        ans = "No"
        break
    if W[x+1] in used:
        ans = "No"
        break
    else:
        used.append(W[x+1])

print(ans)

Measured memory_bytes: 3064
#include <stdio.h>

#define MAX 100
#define NIL -1
#define WHITE 0
#define GRAY 1
#define BLACK 2

void enqueue(int);
int dequeue(void);
void bfs(void);

int head,tail,Queue[MAX];
int color[MAX],M[MAX][MAX],d[MAX],n;

int main(){
  int u,k,v;
  int i,j;

  scanf("%d",&n);

  for (i = 0;i < n;i++){
    scanf("%d %d",&u,&k);

    u--;
    for (j = 0;j < k;j++){
      scanf("%d",&v);

      v--;
      M[u][v] = 1;
    }
  }

  bfs();

  for (i = 0;i < n;i++)
    printf("%d %d\n",i + 1,d[i]);
  
  return 0;
}

void enqueue(int u){
  Queue[tail] = u;

  if (tail + 1 == MAX)
    tail = 0;

  else
    tail++;
}

int dequeue(void){
  int x;

  x = Queue[head];

  if (head + 1 == MAX)
    head = 0;

  else
    head++;

  return x;
}

void bfs(void){
  int u,v;
  int i;

  for (i = 0;i < n;i++){
    color[i] = 0;
    d[i] = NIL;
  }

  color[0] = GRAY;
  d[0] = 0;
  enqueue(0);

  while (head != tail){
    u = dequeue();

    for (v = 0;v < n;v++){
      if (M[u][v] && color[v] == WHITE){
	color[v] = GRAY;
	d[v] = d[u] + 1;
	enqueue(v);
      }
    }

    color[u] = BLACK;
  }
}



Measured memory_bytes: 2112
import java.io.*;
import java.util.StringTokenizer;

class Main{

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n=Integer.parseInt(br.readLine());
		StringTokenizer st=new StringTokenizer(br.readLine());
		int[] in=new int[n];
		for(int i=0;i<n;i++)in[i]=Integer.parseInt(st.nextToken());
		
		int count=0;
		for(int i=0;i<n-1;i++){
			int mini=i;
			for(int j=i+1;j<n;j++){
				if(in[mini]>in[j]){
					mini=j;
				}
				}
			if(mini!=i){
				count++;
			int tmp=in[i];
			in[i]=in[mini];
			in[mini]=tmp;}
		}
		StringBuilder stb=new StringBuilder(Integer.toString(in[0]));
		for(int i=1;i<n;i++)stb.append(" "+in[i]);
		System.out.println(stb+"\r\n"+count);
		
	}

}

Measured memory_bytes: 17004
class UnionFind:
    def __init__(self, size):
        self.par = [-1] * size
        
    def find(self, x):
        if self.par[x] < 0:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y: return False
        if self.par[x] > self.par[y]:
            x, y = y, x
        self.par[x] += self.par[y]
        self.par[y] = x
        return True

    def same(self, x, y):
        return self.find(x) == self.find(y)
    
    def size(self, x):
        return -self.par[self.find(x)]

N, Q = map(int, input().split())
uf = UnionFind(N)
for _ in range(Q):
    t, u, v = map(int, input().split())
    if t == 0:
        uf.unite(u, v)
    else:
        if uf.same(u, v):
            print(1)
        else:
            print(0)

Measured memory_bytes: 11588
import sys
import math
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n = int(readline())
p = list(map(int, input().split()))
ma = int(1e18)

for p_ in p:
    if p_ == 0:
        print(0)
        exit()

ans = 1
for p_ in p:
    ans *= p_
    if ans > ma:
        print(-1)
        exit()
print(ans)


Measured memory_bytes: 21992
import collections


class UnitDict(dict):

    def __init__(self, iterable=None, wrapper=lambda x: x):
        super().__init__(self)
        self.wrapper = wrapper
        if iterable is not None:
            self.update(iterable)

    def __missing__(self, key):
        self[key] = self.wrapper(key)
        return self[key]


class UnionFind(object):

    def __init__(self, nodes=None):
        self.par = UnitDict(wrapper=lambda x: x)
        self.rank = collections.defaultdict(int)
        self.groups = UnitDict(wrapper=lambda x: {x})
        if nodes is not None:
            for node in nodes:
                _, _, _ = self.par[node], self.rank[node], self.groups[node]

    def root(self, node):
        if self.par[node] == node:
            return node
        else:
            r = self.root(self.par[node])
            self.par[node] = r
            return r

    def are_same(self, node1, node2):
        return self.root(node1) == self.root(node2)

    def elements(self, node):
        return self.groups[self.root(node)]

    def size(self, node):
        return len(self.elements(node))

    def unite(self, node1, node2):
        x = self.root(node1)
        y = self.root(node2)
        if x != y:
            if self.rank[x] < self.rank[y]:
                x, y = y, x
            self.par[y] = x
            self.groups[x].update(self.groups[y])
            self.groups[y].clear()
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def grouper(self):
        roots = [x for x in self.par.keys()]
        groups = []
        for root in roots:
            if list(self.elements(root)) not in groups:
                groups.append(list(self.elements(root)))
        return groups


N, M = map(int, input().split())
P = list(map(int, input().split()))
XY = [list(map(int, input().split())) for i in range(M)]

graph = UnionFind(range(N))
for x, y in XY:
    graph.unite(P[x-1], P[y-1])

ans = 0
for i in range(N):
    if P[i] == i+1:
        ans += 1
    elif graph.are_same(i+1, P[i]):
        ans += 1

print(ans)

Measured memory_bytes: 84960
#include<iostream>
#include<map>
#include<vector>
using namespace std;
typedef long long li;
#define rep(i,n) for(int i=0;i<(n);i++)
#define df 0
template<class T> void print(const T& t){ cout << t << "\n"; }
template<class T, class... Ts> void print(const T& t, const Ts&... ts) { cout << t; if (sizeof...(ts)) cout << " "; print(ts...); }
// pair 型
template<class S,class T>
std::ostream& operator<<(std::ostream& os, const pair<T,S>& p){
  cout << "(" << p.first << "," << p.second << ")";
  return os;
}

// map 型
template<class S,class T>
std::ostream& operator<<(std::ostream& os, const map<S,T>& mp){
  for(const pair<S,T>& x: mp){
    cout << "[" << x.first << "]=" << x.second << " ";
  }
  return os;
}
// Container コンテナ型, map以外
template< template<class ...> class Ctn,class T>
std::ostream& operator<<(std::ostream& os,const Ctn<T>& v){
  auto itr=v.begin();
  while(itr!=v.end()){
    if(itr!=v.begin())cout << " ";
    cout << *(itr++);
  }
  return os;
}


int main(){
  int n; cin >>n;
  vector<pair<char,int>> balls(2*n);
  vector<int> posb(n+1),posw(n+1),gtb(n+1),gtw(n+1); // 1-origin
  rep(i,2*n){
    char c; int a; cin >>c >>a;
    balls[i]={c,a};
    ((c=='B')?posb:posw)[a]=i;
    int cnt=0;
    rep(j,i){
      if((balls[j].first != balls[i].first) or
         (balls[j].second > balls[i].second))
        cnt++;
    }
    ((c=='B')?gtb:gtw)[a]=cnt;
  }
  if(df){
    print(balls);
    print(posb);
    print(posw);
    print(gtb);
    print(gtw);
  }
  vector<vector<int>> dp(n+1,vector<int>(n+1,-1));
  dp[0][0]=0;
  rep(i,n){
    dp[0][i+1]=dp[0][i]+gtw[i+1];
    dp[i+1][0]=dp[i][0]+gtb[i+1];
  }
  rep(i,n){
    rep(j,n){
      ((posb[i+1]<posw[j+1])?gtw[j+1]:gtb[i+1])--;
      dp[i+1][j+1]=min(dp[i][j+1]+gtb[i+1],dp[i+1][j]+gtw[j+1]);
    }
    if(df)print(dp[i]);
  }
  print(dp[n][n]);
}


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

#define EB emplace_back
#define int long long
#define F first
#define S second
#define N 100005
#define ALL(x) x.begin(),x.end()
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)


using namespace std;


int32_t main()
{
    IOS;

    int tt=1;
    //cin>>tt;
    while(tt--)
    {
		int sum = 0;
        int n,k; cin>>n>>k; int arr[n]; for(int i = 0; i<n; i++) {
				
			cin>>arr[i];
			sum += arr[i];
		}
		int cnt = 0;
		int test = (sum + 4 * k - 1 ) / (4 * k);
		for (int i = 0; i < n; i++)
		{
			if(arr[i] >= test)  cnt++;
		}
		if(cnt >= k) cout<<"Yes";
		else cout<<"No";

		
		cout<<endl;
    }
    return 0;

}


Measured memory_bytes: 256
// https://atcoder.jp/contests/abc144/tasks/abc144_c
//
#![allow(unused_imports)]
use std::io::*;
use std::fmt::*;
use std::str::*;
use std::cmp::*;
use std::collections::*;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

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

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

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

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

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

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

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

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

#[allow(unused_macros)]
macro_rules! dvec {
    ($t:expr ; $len:expr) => {
        vec![$t; $len]
    };

    ($t:expr ; $len:expr, $($rest:expr),*) => {
        vec![dvec!($t; $($rest),*); $len]
    };
}

#[allow(unused_macros)]
macro_rules! ifv {
    ($t:expr, $a:expr, $b: expr) => {
        if $t { $a } else { $b }
    }
}

#[allow(unused_macros)]
macro_rules! fill {
    ($t:expr, $v:expr) => {
        for i in 0..$t.len() {
            $t[i] = $v;
        }
    };
}

#[allow(unused_macros)]
macro_rules! join {
    ($t:expr, $glue:expr) => {
        $t.into_iter().map(|w| w.to_string()).collect::<Vec<_>>().join($glue)
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn main() {
    input! {
        n: i64
    };

    let mut best = n+10;
    for r in 1..1000010 {
        if n % r == 0 {
            let c = n / r;
            best = min(best, r+c-2);
        }
    }
    println!("{}", best);
}


Measured memory_bytes: 4476
#include <bits/stdc++.h>
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(b) - 1;i>=(a);i--)
#define REP(i,n) for(int i=0;i<(n);i++)
#define RREP(i,n) for(int i=n-1;i>=0;i--)

#define PB push_back
#define INF (1<<29)
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define CLR(a) memset(a,0,sizeof(a))
const int dx[] = {-1,0,0,1},dy[] = {0,1,-1,0};

typedef long long int ll;

using namespace std;

int main(){
    while(true){
	int n,k;
	bool flg = false;
	cin >> n >> k;
	if(n == 0 && k == 0) break;
	vector<bool> a(n+1,false);
	REP(i,k){
	    int temp;
	    cin >> temp;
	    a[temp] = true;
	}
	int ans = 0;
	if(!a[0]){
	    int temp = 0;
	    FOR(i,1,n+1){
		if(a[i]){
		    temp++;
		    ans = max(temp,ans);
		}else temp = 0;
	    }
	}else{
	    int d[2];
	    d[0] = 0;
	    d[1] = 1;
	    FOR(i,1,n+1){
		if(a[i]){
		    d[0]++;
		    d[1]++;
		    ans = max(ans,d[1]);
		}else{
		    d[1] = d[0]+1;
		    d[0] = 0;
		    ans = max(ans,d[1]);
		}
	    }
	}
	cout << ans << endl;
    }
    return 0;
}

Measured memory_bytes: 1208
s=input()
mod=10**9+7
l=len(s)

dp=[[0 for j in range(13)] for i in range(l+1)]
dp[0][0]=1
for i in range(l):
    if s[i] == "?":
        for j in range(10):
            for k in range(13):
                dp[i+1][(k*10+j)%13] += dp[i][k]%mod
    else:
        for k in range(13):
            dp[i+1][(k*10+int(s[i]))%13]+=dp[i][k]%mod
print(dp[-1][5]%mod)

Measured memory_bytes: 66268
macro_rules! scan_sub {
    ( $itr:ident, $t:ty ) => {
        let mut buf = String::new();
        let $itr = {
            while buf.trim().len() == 0 {
                buf = String::new();
                std::io::stdin().read_line(&mut buf).unwrap();
            }
            buf.split_whitespace().map(|n| n.parse::<$t>().unwrap())
        };
    };
}

macro_rules! scan {
    ( $x:ident; Vec<$t:ty> ) => {
        scan_sub!(itr, $t);
        let $x = itr.collect::<Vec<_>>();
    };
    ( $( $x:ident ),*; $t:ty ) => {
        scan_sub!(itr, $t);
        let mut itr = itr;
        $(
            let $x = itr.next().unwrap();
        )*
    };
}

fn main() {
    scan!(n, k; usize);

    let t = n % k;

    println!("{}", if t < k - t {t} else {k - t});
}


Measured memory_bytes: 4352
N, X, Y = list(map(int, input().split()))
X,Y = X-1,Y-1
dist = [[1000]*(m-1) for m in range(N,0,-1)]

for i in range(N-1):
    for j in range(i+1, N):
        dist[i][j-i-1] = min(j-i, abs(X-i)+abs(Y-j)+1)
a = {i:0 for i in range(1, N)}
for dis in dist:
    for d in dis:
        a[d]+=1
for i in range(1, N):
    print(a[i])

Measured memory_bytes: 64604
#Shell sort
def insertionSort(A, n, g, count):
    Acopy = A.copy()
    for i in range(g, n):
        v = Acopy[i]
        j = i - g
        while (j >= 0) and (Acopy[j] > v):
            Acopy[j + g] = Acopy[j]
            j = j - g
            count += 1
        Acopy[j + g] = v
    return Acopy, count

def shellSort(A, n):
    #Gを作成
    G = [1]
    h = 4
    while h < n:
        G.append(h)
        h = 3 * h + 1
    Gr = G.copy()
    Gr.reverse()
    count = 0
    #Gの各要素を使ってSort
    for g in Gr:
        A, count = insertionSort(A, n, g, count)
    return A, Gr, count

n = int(input())
q = 0
A = []
while q < n:
    A.append(int(input()))
    q += 1
A, G, count = shellSort(A, n)
ans = str(len(G)) + '\n' + ' '.join(map(str, G)) + '\n' + str(count) + '\n'
ans += '\n'.join(map(str, A))
print(ans)


Measured memory_bytes: 130856
#include <stdio.h>
#include <string.h>
#define bufsize 1<<22
char ibuf[bufsize];
char *ptr=ibuf;

void readint(int *i)
{
    *i=0;
    while(*ptr>='0')
    {
        *i=*i*10+*ptr-'0';
        ++ptr;
    }
    ++ptr;
}


main()
{
    fread(ibuf,1,bufsize,stdin);

    int h,w,k,sx,sy,tx,ty;
    readint(&h);
    readint(&w);
    readint(&k);
    readint(&sx);
    readint(&sy);
    readint(&tx);
    readint(&ty);
    sx--,sy--,tx--,ty--;

    struct po {int x,y;};
    struct po qu[1<<20];
    struct po *beg=qu,*end=qu+1;
    beg->x=sx,beg->y=sy;
    unsigned int dist[1<<20];
    memset(dist,-1,sizeof(dist));
    dist[sx*w+sy]=0;
    while(beg!=end)
    {
        int x=beg->x,y=beg->y;
        unsigned int d=dist[x*w+y];
        ++beg;
        char *pt=ptr+x*(w+1)+y;
        char *const pcp=pt;
        for(int i=1,a=x,b=y,z=a*w+y; i<=k; i++)
        {
            a++,z+=w;
            pt+=w+1;
            if(a==h||*pt=='@'||dist[z]<=d) break;
            if(a==tx && b==ty)
            {
                printf("%u\n",d+1);
                return 0;
            }
            if(dist[z]!=d+1)
            {
                end->x=a,end->y=b;
                dist[z]=d+1;
                ++end;
            }
        }
        pt=pcp;
        for(int i=1,a=x,b=y,z=a*w+y; i<=k; i++)
        {
            b++,z++;
            pt++;
            if(b==w||*pt=='@'||dist[z]<=d) break;
            if(a==tx && b==ty)
            {
                printf("%u\n",d+1);
                return 0;
            }
            if(dist[z]!=d+1)
            {
                end->x=a,end->y=b;
                dist[z]=d+1;
                ++end;
            }
        }
        pt=pcp;
        for(int i=1,a=x,b=y,z=a*w+y; i<=k; i++)
        {
            a--,z-=w;
            pt-=w+1;
            if(a<0||*pt=='@'||dist[z]<=d) break;
            if(a==tx && b==ty)
            {
                printf("%u\n",d+1);
                return 0;
            }
            if(dist[z]!=d+1)
            {
                end->x=a,end->y=b;
                dist[z]=d+1;
                ++end;
            }
        }
        pt=pcp;
        for(int i=1,a=x,b=y,z=a*w+y; i<=k; i++)
        {
            b--,z--;
            pt--;
            if(b<0||*pt=='@'||dist[z]<=d) break;
            if(a==tx && b==ty)
            {
                printf("%u\n",d+1);
                return 0;
            }
            if(dist[z]!=d+1)
            {
                end->x=a,end->y=b;
                dist[z]=d+1;
                ++end;
            }
        }
    }
    puts("-1");
}


Measured memory_bytes: 11316
#include<bits/stdc++.h>
using namespace std;
#define int long long int
#define I_L_Z_D ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); 
const int N = 1e6 + 5;


int32_t main(){
    I_L_Z_D ;
 	string s;
 	cin >> s;
 	map <char , int > mp;
 	for(auto x : s)mp[x]++;
 	for(auto x : mp){
 		if(x.second != 2 ){
 			cout << "No";
 			return 0;
 		}
 	}	
 	cout << "Yes";
  return 0;
}

Measured memory_bytes: 256
fn solve() {
    let s = std::io::stdin();
    let mut sc = Scanner { stdin: s.lock() };
    let n: usize = sc.read();
    for i in 1..10 {
        for j in 1..10 {
            if i * j == n {
                println!("Yes");
                return;
            }
        }
    }
    println!("No");
}

fn main() {
    std::thread::Builder::new()
        .stack_size(64 * 1024 * 1024) // 64MB
        .spawn(|| solve())
        .unwrap()
        .join()
        .unwrap();
}

//snippet from kenkoooo
pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_line(&mut self) -> String {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b'\n' || b == b'\r')
            .take_while(|&b| b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }

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


Measured memory_bytes: 8572
#include <bits/stdc++.h>
using namespace std;
using ll         = long long;
constexpr ll MOD = 1000000007;
#define REP(i, n) for (ll i = 0; i < (n); i++)
#define REP2(i, x, n) for (ll i = x; i < (n); i++)
#define PR(x) cout << (x) << "\n"
#define PS(x) cout << (x) << " "
#define PRYES(x) PR((x) ? "Yes" : "No")
const long long INF = numeric_limits<long long>::max();
// SourceTest用出力マクロ
#ifdef SOURCE_TEST
#define SPR(x) PR(x)
#define SPS(x) PS(x)
#else
#define SPR(x) \
    {}
#define SPS(x) \
    {}
#endif
int main() {
    ll a, b, c, d;
    cin >> a >> b >> c >> d;

    vector<ll> answers;
    answers.push_back(a * c);
    answers.push_back(a * d);
    answers.push_back(b * c);
    answers.push_back(b * d);
    sort(answers.begin(), answers.end());

    PR(answers[3]);

    return 0;
}

Measured memory_bytes: 3628
<?php

fscanf(STDIN, "%d %d", $n, $m);

$adj_lst = [];
for($i = 0; $i < $m; $i++){
    fscanf(STDIN, "%d %d", $fomr, $nxt);
    $adj_lst[$fomr][] = $nxt;
    $adj_lst[$nxt][] = $fomr;
}

function dfs($p, $visited){
    global $n;
    global $adj_lst;
    $visited[] = $p;

    if(count($visited) == $n) return 1;
    $sum = 0;

    foreach($adj_lst[$p] as $v){
        if(!in_array($v, $visited)) $sum += dfs($v, $visited);
    }

    return $sum;

}

print dfs(1, []);


Measured memory_bytes: 4856
#include <iostream>

using namespace std;
using ll = long long;
using ld = long double;

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

const string YES = "Yes";
const string NO = "No";

int group(ll x) {
  if (x == 2) {
    return 0;
  } else if (x==4||x==6||x==9||x==11) {
    return 1;
  } else {
    return 2;
  }
}

void solve(ll x, ll y) {
  bool pred = group(x) == group(y);
  cout << (pred ? YES : NO) << endl;
}

int main() {
  ll x;
  cin >> x;
  ll y;
  cin >> y;
  solve(x, y);
  return 0;
}


Measured memory_bytes: 256
use itertools::iproduct;
use proconio::{input, marker::Bytes};

fn main() {
    input!(h: usize, w: usize, k: usize, c: [Bytes; h]);

    let test = |b, i| (b >> i) & 1 == 1;

    let ans = iproduct!(0..1 << h, 0..1 << w)
        .filter(|&(bi, bj)| {
            k == iproduct!(0..h, 0..w)
                .filter(|&(i, j)| c[i][j] == b'#' && test(bi, i) && test(bj, j))
                .count()
        })
        .count();

    println!("{}", ans);
}


Measured memory_bytes: 2144