akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <vector>
#include <queue>
#include <cmath>

using namespace std;

const long long INF = 1e18;
const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, -1, 0, 1};

int main(){
    int h, w, k;
    cin >> h >> w >> k;
    int si, sj, ti, tj;
    cin >> si >> sj >> ti >> tj;
    --si; --sj; --ti; --tj;

    vector<string> g(h);
    for(int i=0; i<h; ++i) cin >> g[i];

    auto toId = [&](int i, int j, int v){
        return (i*w+j)*4 +v;
    };

    auto modCeil = [&](long long x){
        //kで割って切り上げ
        return (x+k-1)/k*k;
    };

    vector<long long> dist(h*w*4, INF);

    priority_queue< pair<long long, int>, vector<pair<long long, int> >, greater<pair<long long, int> > >q;
    auto push = [&](int i, int j, int v, long long x){
        int id = toId(i, j, v);
        //もし既存の値のが小さかったら更新しない
        if(dist[id] <= x)return;
        dist[id] = x;
        q.emplace(x, id);
    };

    //init
    for( int v=0; v<4; ++v){
        push(si, sj, v, 0);
    }

    //djikstra
    while(!q.empty()){
        long long d = q.top().first;
        int id = q.top().second;
        q.pop();
        //もし距離が更新されたあとに更新してないとpriorityqueueに残るので、それを飛ばす
        // if(dist[id] != d){
        //     continue;
        // }
        int i = id/w/4;
        int j = id/4%w;
        int v = id%4;
        
        //向きを変える
        for(int nv = 0; nv<4; ++nv){
            push(i, j, nv, modCeil(d));
        }

        //同じ向きに進む
        int ni = i+di[v];
        int nj = j+dj[v];
        //範囲内かつ
        if( 0 <= ni && ni <h && 0<= nj && nj < w){
            //障害物じゃない
            if(g[ni][nj] == '.'){
                push(ni, nj, v, d+1);
            }
        }
    }

    long long ans = INF;
    for(int v=0; v<4; ++v){
        ans = min(ans, dist[toId(ti,tj,v)]);
    }
    if(ans == INF){
        cout << -1 << endl;
    }else{
        ans = modCeil(ans)/k;
        cout << ans << endl;
    }


}

Measured memory_bytes: 44084
#include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


int N;
double dp[501][501];

double recursive(int num_of_rest_type,int know_num){
	if(dp[num_of_rest_type][know_num] != -1.0)return dp[num_of_rest_type][know_num];

	if(num_of_rest_type == know_num)return 0.0;

	double ret = 0.0;
	int num_cards = 2*num_of_rest_type-know_num;

	if(know_num > 0){
		ret += (double)know_num/(double)num_cards*(recursive(num_of_rest_type-1,know_num-1));
	}

	double new_p = (double)(num_cards-know_num)/(double)(num_cards);
	ret += new_p*(1.0/(double)(num_cards-1))*recursive(num_of_rest_type-1,know_num);
	ret += new_p*(double(know_num)/(double)(num_cards-1))*(1.0+recursive(num_of_rest_type-1,know_num));
	if((num_cards-1-(know_num+1) > 0)){
		ret += new_p*((double)(num_cards-1-(know_num+1))/(num_cards-1))*(1.0+recursive(num_of_rest_type,know_num+2));
	}
	return dp[num_of_rest_type][know_num] = ret;
}

void func(){

	printf("%.10lf\n",recursive(N/2,0));
}


int main(){

	for(int i = 0; i <= 500; i++){
		for(int k = 0; k <= 500; k++)dp[i][k] = -1.0;
	}

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

		func();
	}

	return 0;
}

Measured memory_bytes: 5200
#include<iostream>
using namespace std;
int main(){
	int a[100][100], b[100], p[100], d, r, c;
	c = 0;
	cin >> d >> r;
	for (int i = 0; i < d; i = i + 1) {
		b[i] = 0;
		for (int ii = 0; ii < r; ii = ii + 1) {
			p[ii] = 0;
			cin >> a[i][ii];
		}
	}
	for (int i = 0; i < d; i = i + 1) {
		for (int ii = 0; ii < r; ii = ii + 1) {
			b[i] = b[i] + a[i][ii];
			cout << a[i][ii] << " ";
		}
		c = c + b[i];
		cout << b[i] << endl;
	}
	for (int ii = 0; ii < r; ii = ii + 1) {
		for (int i = 0; i < d; i = i + 1) {
			p[ii] = p[ii] + a[i][ii];
		}
		cout << p[ii] << " ";
	}
	cout << c << endl;
}


Measured memory_bytes: 3120
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author david yepes buitrago
 * @date 21-01-2017
 * @time 0.000 ms
 */
public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);
		for (String line; (line = in.readLine()) != null;) {
			int n = Integer.parseInt(line.trim());
			int[] arr = new int[n];
			HashMap<Integer, Boolean> bool = new HashMap<>();
			for (int i = 0; i < n; i++) {
				arr[i] = Integer.parseInt(in.readLine().trim());
				bool.put(arr[i], (i & 1) == 1);
			}
			Arrays.sort(arr);
			int cont = 0;
			for (int i = 0; i < arr.length; i++) {
				if ((i & 1) == 0 == bool.get(arr[i])) {
					cont++;
				}
			}
			out.println(cont >> 1);
		}
		out.close();
	}
}


Measured memory_bytes: 44860
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
int main() {
  long long int N, sum;
  int M, cnt;
  cin >> N >> M;
  
  pair<long long int, int> d[N];

  for(int i = 0;i < N; ++i){
    cin >> d[i].first >> d[i].second;
  }
  sort(d, d+N);
  sum = 0;
  cnt = 0;
  for(int i = 0;i < M; ++i){
    sum += d[cnt].first;
    d[cnt].second--;
    if(d[cnt].second == 0)
      cnt++;
  }
  cout << sum << endl;    
}

Measured memory_bytes: 1792
#include <stdio.h>

struct Dice{
    int num[7];
};

void throwdice(char direction,struct Dice *A){
    int temp;
    switch(direction){
        case 'N' :
            temp = A->num[1];
            A->num[1] = A->num[2];
            A->num[2] = A->num[6];
            A->num[6] = A->num[5];
            A->num[5] = temp;
            break;
        
        case 'E' :
            temp = A->num[1];
            A->num[1] = A->num[4];
            A->num[4] = A->num[6];
            A->num[6] = A->num[3];
            A->num[3] = temp;
            break;
        
        case 'W' :
            temp = A->num[1];
            A->num[1] = A->num[3];
            A->num[3] = A->num[6];
            A->num[6] = A->num[4];
            A->num[4] = temp;
            break;
            
        case 'S' :
            temp = A->num[1];
            A->num[1] = A->num[5];
            A->num[5] = A->num[6];
            A->num[6] = A->num[2];
            A->num[2] = temp;
            break;
    }
}


int main(void){
    struct Dice A;
    int i,j,n,top,front;
    
    for(i=1; i<=6; i++){
        scanf("%d",&A.num[i]);
    }
    
    scanf("%d",&n);
    for(i=0; i<n; i++){
        scanf("%d %d",&top, &front);
        if(front != A.num[2]){
            for(j=0; j<3; j++){
                throwdice('N',&A);
                if(front == A.num[2]) break;
            }
        }
        
        if(front != A.num[2]){
            throwdice('E',&A);
            throwdice('N',&A);
            if(front != A.num[2]){
                throwdice('N',&A);
                throwdice('N',&A);
            }
        }
        
        if(top != A.num[1]){
            for(j=0; j<3; j++){
                throwdice('E',&A);
                if(top == A.num[1]) break;
            }
        }
        
        printf("%d\n",A.num[3]);
    }

    
    return 0;
}

Measured memory_bytes: 596
S = input()
ans1 = ''
ans2 = ''
for i in range(len(S)):
    ans1 += str(i % 2)
    ans2 += str((i+1)%2)
count1 = 0
count2 =0
for i in range(len(S)):
    if S[i] !=ans1[i]: count1 += 1
    if S[i] != ans2[i]: count2 += 1
print(min(count1,count2))

Measured memory_bytes: 3316
#include<bits/stdc++.h>
using namespace std;
#define test int t;cin>>t;while(t--)
void fastcode()
{
    /*
    cout<<fixed<<setprecision(2);
    π = 3.141592653;
    itoa to convert any system itoa(n,bin,2)
    */
    std::ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
}
int main()
{
    /*freopen(" ","r",stdin);
    freopen(" ","w",stdout);*/
    fastcode();
    int t;
    double x;
    cin>>t>>x;
    int z=0;
    while(t--)
    {
        double a,b,c=0;
        cin>>a>>b;
        c=sqrt(pow(a,2)+pow(b,2));
        if(c<=x)
        {
            z++;
        }
    }
    cout<<z;
    return 0;
}


Measured memory_bytes: 3840
#include <bits/stdc++.h>
using namespace std;
#define int long long   // aaaaaaaaaaaaaaaaaa
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define allr(x) (x).rbegin(),(x).rend()
#define in(s,x) s.find(x) != s.end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
#define SIZE(buff) (sizeof(buff)/sizeof(buff[0]))
typedef vector<int> VI;
typedef vector<vector<int> > VVI;
typedef long long ll;
typedef pair<int,int> PII;
typedef vector<pair<int,int>> VPII;
const ll mod=1000000007;
const ll INF= 1LL<<60-1;
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
template<class T> void chmin(T& a,const T& b) { if(a>b) a=b; }
template<class T> void chmax(T& a,const T& b) { if(a<b) a=b; }
template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}
template<typename T, typename U>ostream& operator << (ostream& os, pair<T, U>& pair_var)
{os << pair_var.first << " " << pair_var.second ;return os;}
template<class tContainer>
long long sum(tContainer const& iContainer) {return  std::accumulate(std::begin(iContainer), std::end(iContainer), 0LL);}

// head


int m,n,k,res,tmp,tmp2,tmp3,h,w,x,y;
VI a;
deque<PII> que;
string s;
//VI b;
vector<PII> g[2100600];
int b[2100000];
int c[210] = {};
int rui[210000];
set<int> ch;
VI ab;
VI bb;

signed main() {
	cin.tie(0);
  ios::sync_with_stdio(false);
  cin>>n>>m;
  rep(i,0,n) a.pb(m+i+1-1);
  sort(a.begin(), a.end(), [](int &c, int &d) {
        return abs(c) < abs(d);
    });//比較関数をラムダ式で作る
  res = sum(a);
  cout << res - a[0] << '\n';
}

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

map<pair<pair<int,int>,pair<int,int>>,int> mp;

int func(int *a,int *b,int *c,int i,int fa,int fb,int fc,int n)
{
	if(i==n)
		return 0;
	if(mp.find({{i,fa},{fb,fc}})!=mp.end())
	return mp[{{i,fa},{fb,fc}}];
	int p=INT_MIN,q=INT_MIN,r=INT_MIN;
	if(fa==0)
	p=a[i]+func(a,b,c,i+1,1,0,0,n);
	if(fb==0)
	q=b[i]+func(a,b,c,i+1,0,1,0,n);
	if(fc==0)
	r=c[i]+func(a,b,c,i+1,0,0,1,n);
  	//cout<<p<<" "<<q<<" "<<r<<endl;
	mp[{{i,fa},{fb,fc}}]=max(p,max(q,r));
	return mp[{{i,fa},{fb,fc}}];
}

int main()
{
	int n;
	cin>>n;
	int a[n];
	int b[n];
	int c[n];
	for(int i=0;i<n;i++)
    {
		cin>>a[i];
      	cin>>b[i];
      	cin>>c[i];
    }
	cout<<func(a,b,c,0,0,0,0,n)<<endl;
}


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

using namespace std;

#define ll long long

int main() {
    int n, q, b, e, x, res;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    cin >> q;
    while (q--) {
        cin >> x >> b >> e;
        if (!x) {
            res = INT_MAX;
            for (int i = b; i < e; i++) res = min(res, a[i]);
        } else {
            res=INT_MIN;
            for (int i = b; i < e; i++) res = max(res, a[i]);
        }
        cout << res << endl;
    }
    return 0;
}


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

int main() {
  int a, b;
  cin >> a >> b;
  if(0 < a && a <= b) {
    cout << "Positive" << endl;
  } else if(a <= b && b < 0) {
    if((b - a + 1) % 2 == 0) {
      cout << "Positive" << endl;
    } else {
      cout << "Negative" << endl;
    }
  } else {
    cout << "Zero" << endl;
  }
  return 0;
}

Measured memory_bytes: 256
fun main() = Thread(null, ::abc171e, "(^o^)", 128 * 1024 * 1024).apply { start() }.join()

@OptIn(ExperimentalStdlibApi::class)
fun abc171e() {
    val n = readLine()!!.toInt()
    val aList = readLine()!!.split(' ').map { it.toInt() }

    val cXor = aList.scanReduce(Int::xor).toIntArray()
    val cXorRev = aList.reversed().scanReduce(Int::xor).reversed().toIntArray()

    val answer = (0 until n).map {

        when (it) {
            0 -> cXorRev[1]
            n - 1 -> cXor[it - 1]
            else -> cXor[it - 1] xor cXorRev[it + 1]
        }
    }.joinToString(" ")

    println(answer)
}


Measured memory_bytes: 74016
import itertools

N = int(input())
A = [0] + list(map(int,input().split())) + [0]

acc = []
prev = 0
t = 0
for i in range(N+2):
  if i == 0:
    continue
  a = A[i]
  t += abs(a - prev)
  acc.append(t)
  prev = a
  
ans = []
for i in range(N+1):
  if i == 0:
    continue
  t = 0

  if 1 < i:
    t += acc[i-2]
  if i < N:
    t += acc[N] - acc[i]
  t += abs(A[i+1] - A[i-1])
    
  ans.append(t)
  
print("\n".join(map(str,ans)))


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

#define int long long
#define rep(i, n) for (int i = 0; i < (int) (n); i++)
#define reps(i, n) for (int i = 1; i <= (int) (n); i++)
#define all(x) (x).begin(), (x).end()
#define uniq(x) (x).erase(unique(all(x)), (x).end()))
#define bit(n) (1LL << (n))
#define cdiv(a, b) (((a) - 1) / (b) + 1)
#define dump(x) cerr << #x " = " << (x) << endl
using vint = vector<int>;
using vvint = vector<vint>;
using pint = pair<int, int>;
using vpint = vector<pint>;
template<typename T> using priority_queue_rev = priority_queue<T, vector<T>, greater<T>>;
constexpr double PI = 3.1415926535897932384626433832795028;
constexpr int DY[8] = {0, 1, 0, -1, 1, 1, -1, -1};
constexpr int DX[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int gcd(int a, int b) {
    while (b) { swap(a %= b, b); }
    return a;
}
int lcm(int a, int b) { return a / gcd(a, b) * b; }
template<typename T> void fin(T mes) {
    cout << mes << endl;
    exit(0);
}
template<typename T, typename U> bool chmax(T &a, const U &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template<typename T, typename U> bool chmin(T &a, const U &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}
template<typename T, typename U> ostream &operator<<(ostream &os, const pair<T, U> &rhs) {
    os << "(" << rhs.first << ", " << rhs.second << ")";
    return os;
}
template<typename T> ostream &operator<<(ostream &os, const vector<T> &rhs) {
    os << "{";
    for (auto itr = rhs.begin(); itr != rhs.end(); itr++) {
        os << *itr << (next(itr) != rhs.end() ? ", " : "");
    }
    os << "}";
    return os;
}
struct setup {
    static constexpr int PREC = 20;
    setup() {
        cout << fixed << setprecision(PREC);
        cerr << fixed << setprecision(PREC);
    };
} setup;

signed main() {
    int N;
    cin >> N;
    vint V(N + 1), W(N + 1);
    reps(i, N) { cin >> V[i] >> W[i]; }
    int m = min(bit(9) - 1, N);
    vvint dp(m + 1, vint(110000));
    reps(i, m) {
        rep(j, 110000) {
            chmax(dp[i][j], dp[i / 2][j]);
            if (j >= W[i]) { chmax(dp[i][j], dp[i / 2][j - W[i]] + V[i]); }
        }
    }
    int Q;
    cin >> Q;
    rep(i, Q) {
        int v, L;
        cin >> v >> L;
        vint Vc, Wc;
        while (v >= m) { Vc.push_back(V[v]), Wc.push_back(W[v]), v >>= 1; }
        int ans = 0;
        rep(j, bit(Vc.size())) {
            int Vsum = 0, Wsum = 0;
            rep(k, Vc.size()) { if (j & bit(k)) { Vsum += Vc[k], Wsum += Wc[k]; }}
            if (Wsum > L) { continue; }
            chmax(ans, dp[v][L - Wsum] + Vsum);
        }
        cout << ans << '\n';
    }
}


Measured memory_bytes: 448624
// ConsoleApplication3.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
//

//#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
	int a, b,c;
	cin >> a >> b >> c;
	if (a < b && b < c) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}
    return 0;
}




Measured memory_bytes: 3096
#include<bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define F first
#define S second
#define ll long long
#define ld long double
#define sz(a) ((int)(a).size())
#define clr(a,v) memset(a, v, sizeof(a))
#define all(a) (a).begin(),(a).end()
#define pii pair<int,int>
#define pdd pair<ld,ld> 
#define rep(i,a,b) for(int i=a; i<b; i++)
#define dec(i,a,b) for(int i=a; i>=b; i--)
#define ler freopen("inspection.in","r",stdin);freopen("inspection.out","w",stdout)
#define fastio ios::sync_with_stdio(0), cin.tie(0)
#define debug cout<<"!!?!!\n"
using namespace std;
#define MAXN 100005
#define INF 2000000000000000000LL
#define inf 1000010000
ll a, b, n, v[MAXN];

bool detonou(ll mid){
	ll cont=0;
	rep(i,0,n){
		if(v[i] > mid*b) cont+= (v[i]-mid*b+a-1)/a;
	}
	return cont<=mid;
}

int main(){
	cin >> n >> a >> b; 
	a-=b;
	rep(i,0,n) cin >> v[i];
	
	ll bot=0, top=inf, mid;
	while(top-bot>1){
		mid= (top+bot)/2;
		if(detonou(mid)) top=mid;
		else bot=mid;
	}
	if(detonou(bot)) top=bot;
	cout << top << endl;
}








Measured memory_bytes: 1024
#061_C
n, k = map(int, input().split())
pair = []
for _ in range(n):
    a, b = map(int, input().split())
    pair.append((a, b))
pair.sort()

tmp = 0
for a, b  in pair:
    tmp += b
    if k <= tmp:
        print(a)
        break

Measured memory_bytes: 16940
import itertools
N = int(input())
P = list(map(int,input().split()))
Q = list(map(int,input().split()))
S = sorted(list(itertools.permutations(P)))
S = [list(item) for item in S]
count = 0
nump = 0
numq = 0


for item in S:
    check = 0
    for i in range(N):
        if item[i] == P[i]:
            check+=1       
    if check == N:
        nump = count
        
    check = 0
    for i in range(N):
        if item[i] == Q[i]:
            check+=1
    if check == N:
        numq = count
    count += 1
    
print(abs(nump-numq))


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

int main(){
    int a, b, c, s;
    cin >> a >> b >> c;
    
    s = 0;
    for (int i = a; i <= b ; i++){
        if(c % i == 0){
            s++;
        }
    }
    cout << s << endl;
}


Measured memory_bytes: 3096
import std.stdio, std.conv, std.string;
import std.algorithm, std.array, std.container;
import std.numeric, std.math;
import core.bitop;

T RD(T = string)() { static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res.to!T; }
string RDR()() { return readln.chomp; }
T[] ARR(T)(in string str) { return str.split.to!(T[]); }

long mod = pow(10, 9) + 7;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }

struct UnionFind
{
	void init(long n) { par = new long[](n); foreach (i; 0..n) par[i] = i; }
	long root(long i) { return par[i] == i ? i : (par[i] = root(par[i])); }
	bool same(long i, long j) { return root(i) == root(j); }
	void unite(long i, long j) { i = root(i); j = root(j); if (i == j) return; par[i] = j; }
	long[] par;
}

void main()
{
	auto N = RD!long;
	auto M = RD!long;
	auto p = RDR.ARR!(long);
	p[] -= 1;
	UnionFind uf;
	uf.init(N);
	foreach (i; 0..M)
	{
		auto x = RD!long - 1;
		auto y = RD!long - 1;
		uf.unite(x, y);
	}

	long ans;
	foreach (i; 0..N)
	{
		if (p[i] == i) ++ans;
		else if (uf.same(p[i], i)) ++ans;
	}

	writeln(ans);
	stdout.flush();
}

Measured memory_bytes: 5436
#include "bits/stdc++.h"
using namespace std;

const int N = 2 * 1e5 + 5;
int a[N], b[N];
deque<int> d;

int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
        if(i&1) d.push_front(a[i]);
        else d.push_back(a[i]);
    }

    if(n&1) reverse(d.begin(), d.end());
    for(int i = 0; i < d.size(); i++)
    {
        cout << d[i] << ' ';
    }
}


Measured memory_bytes: 3840
#include <cstdio>
#include <cstdint>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <array>
#include <vector>
#include <unordered_map>

struct Node {
    Node() :
        parent(nullptr),
        left(nullptr),
        right(nullptr),
        id(-1)
    {
    }

    Node* parent;
    Node* left;
    Node* right;
    int   id;
};

void preorder(const Node& node)
{
    std::printf(" %d", node.id);
    if (node.left != nullptr) {
        preorder(*(node.left));
    }

    if (node.right != nullptr) {
        preorder(*(node.right));
    }
}

void inorder(const Node& node)
{
    if (node.left != nullptr) {
        inorder(*(node.left));
    }

    std::printf(" %d", node.id);

    if (node.right != nullptr) {
        inorder(*(node.right));
    }
}

void postorder(const Node& node)
{
    if (node.left != nullptr) {
        postorder(*(node.left));
    }


    if (node.right != nullptr) {
        postorder(*(node.right));
    }

    std::printf(" %d", node.id);
}

int main()
{
    int n;
    std::cin >> n;
    Node nodes[n];

    int id, l, r;
    for (int i = 0; i < n; ++i) {
        std::cin >> id >> l >> r;
        nodes[id].id = id;
        if (l != -1) {
            nodes[id].left = &(nodes[l]);
            nodes[l].parent = &(nodes[id]);
        }

        if (r != -1) {
            nodes[id].right = &(nodes[r]);
            nodes[r].parent = &(nodes[id]);
        }

    }

    Node* root = nullptr;
    for (int i = 0; i < n; ++i) {
        if (nodes[i].parent == nullptr) {
            root = &(nodes[i]);
            break;
        }
    }

    std::cout << "Preorder"  << std::endl;
    preorder(*root);

    std::cout << "\nInorder"   << std::endl;
    inorder(*root);

    std::cout << "\nPostorder" << std::endl;
    postorder(*root);

    std::cout << std::endl;

    return 0;
}


Measured memory_bytes: 3212
import sys
from sys import exit
from collections import deque
from bisect import bisect_left, bisect_right, insort_left, insort_right #func(リスト,値)
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def perm(n,mod=None):
    ans = 1
    for i in range(1,n+1):
        ans *= i
        if mod!=None:
            ans %= mod
    return ans
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x):
        self.setdefault(x,0)
        self[x] += 1
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]

N,M = mint()
S = [lint() for _ in range(M)]
P = lint()
ans = 0
for k in range(1<<N):
    tmp = [(k>>i)&1 for i in range(N)]
    now = True
    for s,p in zip(S,P):
        on = 0
        for i in s[1:]:
            on += tmp[i-1]
        if on%2!=p:
            now = False
            break
    ans = ans+1 if now else ans
print(ans)

Measured memory_bytes: 75112
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <cstring>
#include <climits>
#include <cmath>
#include <cfloat>

#define FOR(i,b,n) for(int i=b;i<n;i++)
#define CLR(mat) memset(mat, 0, sizeof(mat))
#define INF 1<<25

using namespace std;

string str, rstr;

int main()
{
	while( cin >> str, !cin.eof())
	{
		rstr = string( str.rbegin() , str.rend() );

		cout << rstr << endl;
	}

	return 0;
}

Measured memory_bytes: 0
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
#define N_MAX 100005
typedef long long ll;
ll s[N_MAX];
ll t[N_MAX];
ll x[N_MAX];
ll ans[8];
int main() {
	int A, B, Q;
	cin >> A >> B >> Q;
  	for(int i = 0; i < A; i++){
    	cin >> s[i];
    }
  	for(int i = 0; i < B; i++){
    	cin >> t[i];
    }
  	for(int i = 0; i < Q; i++){
    	cin >> x[i];
    }
	for(int i = 0; i < Q; i++){
        int l = 0;
        int r = A-1;
        while(r-l > 1){
            int mid = (l+r)/2;
            if(s[mid] < x[i]){
                l = mid;	
            } else {
                r = mid;
            }
        }
        ll s_l = s[l];
        ll s_h = s[r];

        l = 0;
        r = B-1;
        while(r-l > 1){
            int mid = (l+r)/2;
            if(t[mid] < x[i]){
                l = mid;	
            } else {
                r = mid;
            }
        }
        ll t_l = t[l];
        ll t_h = t[r];
      	ll answer = 9223372036854775807;
      	ans[0] = abs(t_h-s_h)+abs(s_h-x[i]);
      	ans[1] = abs(s_h-t_h)+abs(t_h-x[i]);
      	ans[2] = abs(t_l-s_l)+abs(s_l-x[i]);
        ans[3] = abs(s_l-t_l)+abs(t_l-x[i]);
      	ans[4] = abs(t_h-s_l)+abs(s_l-x[i]);
      	ans[5] = abs(t_l-s_h)+abs(s_h-x[i]);
      	ans[6] = abs(s_l-t_h)+abs(t_h-x[i]);
      	ans[7] = abs(s_h-t_l)+abs(t_l-x[i]);
      	for(int j = 0; j < 8; j++){
        	if(answer > ans[j]) answer = ans[j];
        }
	cout << answer << endl;
    }
}

Measured memory_bytes: 3712
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int > pre,inorder,post;
int pos;
void rec(int l,int r){
    if(l>=r)return;
    int root = pre[pos++];
    int m = distance(inorder.begin(),find(inorder.begin(),inorder.end(),root));
    rec(l,m);
    rec(m+1,r);
    post.push_back(root);
}
int main(){
    int n,k;
    pos=0;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>k;
        pre.push_back(k);
    }
    for(int i=0;i<n;i++)
    {
        cin>>k;
        inorder.push_back(k);
    }
    rec(0,n);
    int isn=0;
    for(int i=0;i<n;i++)
    {
        if(isn++>0)
            cout<<' ';
        cout<<post[i];
    }
    cout<<endl;
    return 0;
}


Measured memory_bytes: 3168
#include<stdio.h>
#define N 8

int D[N][N]={0};

void printP(){
  int i,j;

  for(i=0;i<N;i++){
    for(j=0;j<N;j++){
      if(D[i][j] == 1){
	printf("Q");
      }
      else printf(".");
    }
    printf("\n");
  }
}

int cal(int b,int a){
  int i,j;

  for(i=0;i<N;i++){
    if(i!=a && D[b][i]==1){
      return 0;
    }
  }
  for(i=0;i<N;i++){
    if(i!=b &&D[i][a]==1){
      return 0;
    }
  }
  i=b-1;
  j=a+1;
  while(i>=0 && j<N){
    if(D[i--][j++]==1){
      return 0;
    }
  }
  i=b-1;
  j=a-1;
  while(i>=0 && j>=0){
    if(D[i--][j--]==1){
      return 0;
    }
  }

  i=b+1;
  j=a-1;

  while(i<N && j>=0){
    if(D[i++][j--]==1){
      return 0;
    }
  }

  i=b+1;
  j=a+1;
  while(i<N && j<N){
    if(D[i++][j++]==1){
      return 0;
    }
  }

  return 1;
}

int Get(int X){
  int i;

  for(i=0;i<N;i++){
    if(D[X][i]==1){
      if(!Get(X+1)){
	return 0;
      }
    }
  }

  if(X==N){
    printP();
    return 1;
  }
  else {
    for(i=0;i<N;i++){
      if(D[X][i]==0 && cal(X,i)){
	D[X][i]=1;
	if(!Get(X+1)){
	  D[X][i]=0;
	}
      }
    }
  }

  return 0;
}

int main(){
  int num,i,j,x,y,X=0;

  scanf("%d",&num);

  for(i=0;i<num;i++){
    scanf("%d %d",&y,&x);
    D[y][x]=1;
  }
  i=Get(X);

  return 0;
}
    



Measured memory_bytes: 2112
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <numeric>
#include <iomanip>
#include <bitset>
 
using namespace std;
 
typedef long long ll;
 
ll dp[60][60][3000];
 
int main(){
    int N, A;
    cin >> N >> A;
    vector<int> x(N);
    for(int i = 0; i < N; i++){
        cin >> x[i];
    }
    
    // 組み合わせの公式（パスカルの三角形）
    for(int i = 0; i <= N; i++){
        for(int j = 0; j <= N; j++){
            for(int k = 0; k <= N * 50; k++){
                if(i == 0 && j == 0 && k == 0){
                    dp[i][j][k] = 1;
                }
                else if(i >= 1 && k < x[i - 1]){
                    dp[i][j][k] = dp[i - 1][j][k];
                }
                else if(i >= 1 && j >= 1 && k >= x[i - 1]){
                    dp[i][j][k] = dp[i - 1][j][k] + dp[i - 1][j - 1][k - x[i - 1]];
                }
                else{
                    dp[i][j][k] = 0;
                }
            }
        }
    }
    
    // for(int i = 0; i <= N; i++){
    //     for(int j = 0; j <= N; j++){
    //         cout << i << " " << j << endl;
    //         for(int k = 0; k <= (i + 1) * A; k++){
    //             cout << dp[i][j][k] << " ";
    //         }
    //         cout << endl;
    //     }
    //     cout << endl;
    // }
    
    ll ans = 0;
    for(int i = 1; i <= N; i++){
        ans += dp[N][i][i * A];
        // cout << dp[N][i][i * A] << " ";
    }
    // cout << endl;
    
    cout << ans << endl;
}

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

#define rep(i,j,n) for(int i=j;i<n;++i)
#define all(i) i.begin(),i.end()
#define rall(i) i.rbegin(), i.rend()
#define INF 1e9
#define LINF 1e18
const int mod = 1e9 + 7;

typedef long long i64;
typedef pair<int, int> pi;

template <class T> using vt = vector<T>;
template <class T> using vvt = vector<vector<T>>;

i64 gcd(i64 n, i64 m) {return (m == 0? n : gcd(m, n % m));}
i64 lcd(i64 n, i64 m) {return (n / gcd(n, m) * m);}
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};

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

	int n, k, s;
	cin >> n >> k >> s;

	vt<int> a(n);
	rep(i, 0, k) a[i] = s;
	int num = s + 1;
	if(s == 1e9) num = 1;
	rep(i, k, n) a[i] = num;

	rep(i, 0, n) cout << a[i] << " \n"[i == n - 1];
}

Measured memory_bytes: 1664
n, m = map(int, input().split())
WV = [tuple(map(int, input().split())) for i in range(n)]
W = [w for w, v in WV]
V = [v for w, v in WV]
DP = [[0 for j in range(m+1)] for i in range(n+1)]
for i in range(n):
    for j in range(W[i]):
        DP[i+1][j] = DP[i][j]
    for j in range(W[i], m+1):
        DP[i+1][j] = max(DP[i][j], DP[i][j-W[i]]+V[i])
print(DP[n][m])


Measured memory_bytes: 171528
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<int, int>;
using PLL = pair<ll, ll>;
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define repn(i,n) for(int i = 0; i <= (int)(n); i++)
#define srep(i,l,n) for(int i = l; i < (int)(n); i++)
#define srepn(i,l,n) for(int i = l; i <= (int)(n); i++)
#define drep(i,n) for(int i = (int)(n-1); i >= 0; i--)
#define drepn(i,n) for(int i = (int)(n); i >= 0; i--)
#define size(s) (int)s.size()
#define debug(var)  do{std::cout << #var << " : ";view(var);}while(0)
template<typename T> void view(T e){std::cout << e << std::endl;}
template<typename T> void view(const std::vector<T>& v){for(const auto& e : v){ std::cout << e << " "; } std::cout << std::endl;}
template<typename T> void view(const std::vector<std::vector<T> >& vv){ for(const auto& v : vv){ view(v); } }
template<typename T> inline istream& operator>>(istream &i, vector<T> &v) {rep(j, size(v)) i >> v[j]; return i;}
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
template<class T> T gcd(T a, T b) {if(b==0)return a; else return gcd(b,a%b);}
template<class T> T lcm(T a, T b) {return a/gcd(a,b)*b;}
template<class T = int> using V = vector<T>;
template<class T = int> using VV = vector<V<T>>;
bool isIn(int i, int j, int h, int w) {return i >= 0 && i < h && j >= 0 && j < w;}
void Yes(){cout << "Yes" << endl;}
void No(){cout << "No" << endl;}
void YES(){cout << "YES" << endl;}
void NO(){cout << "NO" << endl;}
void err() {cout << -1 << endl;}
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
#define ep emplace_back

const int MOD = 1000000007;
const int INF = 1e9;

#define PI acos(-1);
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int ddx[8] = {1,1,1,-1,-1,-1,0,0};
int ddy[8] = {0,1,-1,0,1,-1,1,-1};


int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    string s;
    cin >> s;
    bool N, E, W, S;
    N = E = W = S = false;
    for(char c : s) {
        if(c == 'N') N = true;
        if(c == 'E') E = true;
        if(c == 'W') W = true;
        if(c == 'S') S = true;
    }
    bool ok = true;
    if(N ^ S) ok = false;
    if(E ^ W) ok = false;
    if(ok) cout << "Yes" << '\n';
    else cout << "No" << '\n';
}

Measured memory_bytes: 3580
import java.util.*;
 
public class Main {
    public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=0;
int c=1;
int d=1;
int e=1;
int r;
for(int i=1;i<=a;i++){
   for(int j=1;j<=a;j++){
       for(int k=1;k<=a;k++){
while((r=c%d)!=0){
    c=d;
    d=r;
}
while((r=d%e)!=0){
    d=e;
    e=r;
}
b+=e;
c=k;
d=j;
e=i;
    c+=1;
}
       c=1;
    d+=1;
}
    d=1;
    e+=1;
}
System.out.println(b);
}
}

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

typedef long long int int64;

int comp(const void *a, const void *b)
{
    return *(int *)a - *(int *)b;
}

int main(int argc, char **argv)
{
    int N, K;
    cin >> N >> K;
    int H[N];
    for (int i = 0; i < N; ++i) cin >> H[i];

    qsort(H, N, sizeof(int), comp);

    if (N <= K) cout << 0;
    else {
        int64 sum = 0;
        for (int i = 0; i < N - K; ++i) sum += H[i];
        cout << sum;
    }

    return 0;
}


Measured memory_bytes: 1788
#[allow(dead_code)]
fn main() {
    let n = i::u();
    let ab = i::uv2(n);

    let mut small: Vec<_> = ab.iter().map(|(a, b)| a).cloned().collect();
    let mut big: Vec<_> = ab.iter().map(|(a, b)| b).cloned().collect();
    small.sort();
    big.sort();

    if n % 2 == 0 {
        let s = small[n / 2] + small[n / 2 - 1];
        let b = big[n / 2] + big[n / 2 - 1];
        println!("{}", (b - s) + 1);
    //dbg!(&s, &b);
    } else {
        let s = small[n / 2];
        let b = big[n / 2];
        println!("{}", b - s + 1);
        //dbg!(&s, &b);
    }
}

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::*;
#[allow(unused_imports)]
use std::num::*;
#[allow(unused_imports)]
use std::str::*;

#[allow(dead_code)]
mod i {
    use super::*;

    pub fn read<T: FromStr>() -> T {
        stdin()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>()
            .parse::<T>()
            .ok()
            .unwrap()
    }
    pub fn str() -> String {
        read()
    }
    pub fn s() -> Vec<char> {
        str().chars().collect()
    }
    pub fn i() -> i64 {
        read()
    }

    pub fn u() -> usize {
        read()
    }

    pub fn u2() -> (usize, usize) {
        (read(), read())
    }

    pub fn u3() -> (usize, usize, usize) {
        (read(), read(), read())
    }

    pub fn u4() -> (usize, usize, usize, usize) {
        (read(), read(), read(), read())
    }

    pub fn u5() -> (usize, usize, usize, usize, usize) {
        (read(), read(), read(), read(), read())
    }

    pub fn u6() -> (usize, usize, usize, usize, usize, usize) {
        (read(), read(), read(), read(), read(), read())
    }

    pub fn f() -> f64 {
        read()
    }

    pub fn c() -> char {
        read::<String>().pop().unwrap()
    }

    pub fn iv(n: usize) -> Vec<i64> {
        (0..n).map(|_| i()).collect()
    }

    pub fn iv2(n: usize) -> Vec<(i64, i64)> {
        (0..n).map(|_| iv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn iv3(n: usize) -> Vec<(i64, i64, i64)> {
        (0..n).map(|_| iv(3)).map(|a| (a[0], a[1], a[2])).collect()
    }

    pub fn uv(n: usize) -> Vec<usize> {
        (0..n).map(|_| u()).collect()
    }

    pub fn uv2(n: usize) -> Vec<(usize, usize)> {
        (0..n).map(|_| uv(2)).map(|a| (a[0], a[1])).collect()
    }

    pub fn uv3(n: usize) -> Vec<(usize, usize, usize)> {
        (0..n).map(|_| uv(3)).map(|a| (a[0], a[1], a[2])).collect()
    }

    pub fn uv4(n: usize) -> Vec<(usize, usize, usize, usize)> {
        (0..n)
            .map(|_| uv(4))
            .map(|a| (a[0], a[1], a[2], a[3]))
            .collect()
    }

    pub fn fv(n: usize) -> Vec<f64> {
        (0..n).map(|_| f()).collect()
    }

    pub fn cmap(h: usize) -> Vec<Vec<char>> {
        (0..h).map(|_| s()).collect()
    }
}


Measured memory_bytes: 8948
import java.util.Scanner;
import java.util.*;
import java.lang.*;

class Main{
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    long x = scanner.nextLong(); 
    long y = scanner.nextLong();
    if(x<y){
      long d = Math.abs(x-y);
      if(x>d){
      	System.out.print(d);
       }
   	   else{
     	 System.out.print(x);}
    }
    else{
      long a = x%y;
      if(a==0){
        System.out.print(a);
      }
      else{
        long b = Math.abs(a-y);
        if(a>b){
      		System.out.print(b);
        }
        else{
          System.out.print(a);
        }
      }
    }
  }
}

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

const ll mod = 1000000007;
const double eps = 1e-8;
const ll INF = 1e16;

#ifdef DEBUG
#include "inc/debug.hpp"
#else
#define debug(...) 42
#endif

template<typename A, size_t N, typename T>
void st_fill(A (&arr)[N], const T &val){ fill((T*)arr, (T*)(arr+N), val); }
void chmax(ll &a, ll b) { a = max(a, b); }

ll dp[200010][2][3];

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

    st_fill(dp, -INF);

    int r = 1 + (N % 2);
    dp[0][0][r-1] = 0;
    dp[0][1][r] = A[0];
    for (int i=1; i<N; ++i) {
        for (int j=0; j<3; ++j) {
            chmax(dp[i][1][j], dp[i-1][0][j] + A[i]);
            chmax(dp[i][0][j], dp[i-1][1][j]);
            if (j > 0) chmax(dp[i][0][j-1], dp[i-1][0][j]);
        }
    }

    ll res = -INF;
    for (int i=0; i<2; ++i) {
        for (int j=0; j<3; ++j) {
            res = max(res, dp[N-1][i][j]);
        }
    }
    cout << res << endl;

    return 0;
}

Measured memory_bytes: 14348
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<utility>
#include<tuple>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>

using namespace std;

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

#define BIL ((ll)1e9)
#define MOD ((ll)1e9+7)
#define INF (1LL<<60)           //1LL<<63でオーバーフロー
#define inf (1<<29)             //1<<29でオーバーフロー

int main(int argc,char* argv[]){
    ll q,h,s,d,n;
    cin >> q >> h >> s >> d >> n;

    q*=4;
    h*=2;

    ll ans=0;
    if(min(2*q,min(2*h,min(2*s,d)))==d){
        ans+=n/2*d;
        if(n%2!=0){
            ans+=min(q,min(h,s));
        }
    }else{
        ans+=n*min(q,min(h,s));
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 3612
using System;
using System.Linq;
using System.Collections.Generic;
using static System.Console;
using System.Text;
using System.IO;
using static System.Math;
namespace AtCoder
{
    class Program
    {
        static public long[] Sarray() { return ReadLine().Split().Select(long.Parse).ToArray(); }
        static public List<long> Slist() { return ReadLine().Split().Select(long.Parse).ToList(); }

        static long Mod = (long)1e9 + 7;
        static void Main(string[] args)
        {
            //SetOut(new StreamWriter(OpenStandardOutput()) { AutoFlush = false });
            var NM = Sarray();
            var N = NM[0];
            var M = NM[1];
            if (1 < Abs(N - M))
            {
                WriteLine(0);
                return;
            }
            var ans = 1L;
            //最初が犬か猿かで分けれる
            if (N == M)
                ans = 2;
            for (var i = N; 0 < i; --i)
                ans = (ans * i) % Mod;
            for (var i = M; 0 < i; --i)
                ans = (ans * i) % Mod;
            WriteLine(ans % Mod);
            //Out.Flush();
        }
    }
}

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

#define fio                           \
	ios_base::sync_with_stdio(false); \
	cin.tie(NULL);                    \
	cout.tie(NULL);
#define ll long long
#define ull unsigned long long
#define ld long double
#define endl "\n"
#define ff first
#define ss second
#define pi pair<ll, ll>
#define PI 3.141592653589793238462643383279502884L
#define mp make_pair
#define pb push_back
#define fall(i, a, b) for (int i = a; i < b; i++)
#define sz(x) (ll) x.size()
#define all(x) x.begin(), x.end()
#define ed cout << "ed";
#define time_passed 1.0 * clock() / CLOCKS_PER_SEC
ll MOD = 1e9 + 7;
ll MOD1 = 1e9 + 123;
ll MOD2 = 1e9 + 321;

int main()
{
	fio;
	ll t, a, n, q, k, i, l, m, c, u, f, j, p, r, x, y, s, b, d;
	ll N, W;
	cin >> N >> W;
	vector<int> vn(N, 0), vw(N, 0);
	for (i = 0; i < N; i++)
		cin >> vw[i] >> vn[i];
	vector<vector<ll>> dp(N + 1, vector<ll>(W + 1,0));
	for (i = 1; i <= N; i++)
		for (j = 1; j <= W; j++)
			if (vw[i - 1] <= j)
				dp[i][j] = max(vn[i - 1] + dp[i - 1][j - vw[i - 1]], dp[i - 1][j]);
			else
				dp[i][j] = dp[i - 1][j];
	cout << dp[N][W];
	return 0;
}


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

int main()
{
	int M, T, P, R;
	while (cin >> M >> T >> P >> R)
	{
		if (M == 0&& T == 0 && P == 0 && R == 0)break;

		vector<int> teamID(T);
		for (int i = 0; i < T; i++)
		{
			teamID[i] = i;
		}
		int wrong[50][10];
		for (int i = 0; i < T; i++)
		{
			for (int j = 0; j < P; j++)
			{
				wrong[i][j] = 0;
			}
		}
		vector<int> correct(T);
		vector<int> time(T);


		for (int i = 0; i < R; i++)
		{
			int m, t, p, j;
			cin >> m >> t >> p >> j;
			t--;
			p--;
			if (j == 0)
			{
				correct.at(t)++;
				time.at(t) += m + wrong[t][p] * 20;
			}
			else
			{
				wrong[t][p]++;
			}
		}

		for (int i = 0; i < T - 1; i++)
		{
			for (int j = i + 1; j < T; j++)
			{
				if (correct.at(teamID[i]) < correct.at(teamID[j])
					|| (correct.at(teamID[i]) == correct.at(teamID[j]) && time.at(teamID[i]) > time.at(teamID[j]))
					|| (correct.at(teamID[i]) == correct.at(teamID[j]) && time.at(teamID[i]) == time.at(teamID[j]) && teamID[i] < teamID[j]))
				{
					int tmp = teamID[i];
					teamID[i] = teamID[j];
					teamID[j] = tmp;
				}
			}
		}

		for (int i = 0; i < T; i++)
		{
			if (i > 0 && correct.at(teamID[i]) == correct.at(teamID[i - 1]) && time.at(teamID[i]) == time.at(teamID[i - 1]))
			{
				cout << "=";
			}

			cout << (teamID[i] + 1);

			if (i < T - 1 && 
				!(correct.at(teamID[i]) == correct.at(teamID[i + 1]) && time.at(teamID[i]) == time.at(teamID[i + 1])))
			{
				cout << ",";
			}
		}

		cout << endl;


	}
	return 0;
}

Measured memory_bytes: 1200
n = input()
d = list(map(int,input().split()))
d_sort = sorted(d)
sa = (d_sort[int(len(d_sort) / 2)]) - (d_sort[int(len(d_sort) / 2) - 1])
arc =d_sort[int(len(d_sort) / 2):]
abc = d_sort[0:(int(len(d_sort) / 2))]
if len(arc) == len(abc):
    print(sa)
else:
    print(0)



Measured memory_bytes: 14008
import sys
import numpy as np
# input処理を高速化する
input = sys.stdin.readline

L=int(input())

#forループではない
# div =0.001
# ranges =np.arange(0.001,L+1,0.01)
# V=0
# for x in ranges:
#     z=L-2*x
#     V=max(V,x*x*z)

# print(V)
#相加相乗平均を用いる
print((L/3)**3)

Measured memory_bytes: 12388
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int temp(int a,int b)
{
	return a>b;
}
int main()
{
	int x=0,sum1=0,sum2=0,n,a[5000];
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	  scanf("%d",&a[i]);
	sort(a+1,a+n+1,temp);
	for(int i=1;i<=n;i++)
	{
		if(x%2==1)
		  sum1+=a[i];
		else sum2+=a[i];
		x++;
	}
	cout<<abs(sum1-sum2)<<endl;
}

Measured memory_bytes: 256
package main

import (
	"fmt"
)

// A - Frog 1
// https://atcoder.jp/contests/dp/tasks/dp_a

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

func max(x1 int, x2 int) int {
	if x1 < x2 {
		return x2
	}
	return x1
}

func min(x1 int, x2 int) int {
	if x1 < x2 {
		return x1
	}
	return x2
}

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	h := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &h[i])
	}
	var dp = make([]int, n)
	dp[0] = 0
	var num = min(k+1, n)
	for i := 1; i < num; i++ {
		dp[i] = abs(h[i] - h[0])
	}
	var tmp = 0
	for i := k; i < n; i++ {
		dp[i] = dp[i-1] + abs(h[i]-h[i-1])
		for j := 2; j <= k; j++ {
			tmp = dp[i-j] + abs(h[i]-h[i-j])
			dp[i] = min(tmp, dp[i])
		}
	}
	fmt.Printf("%d\n", dp[n-1])
}


Measured memory_bytes: 6324
#include<bits/stdc++.h>
 
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define EPS (1e-10)
#define equals(a,b) (fabs((a)-(b))<EPS)
 
using namespace std;

bool LT(double a,double b) { return !equals(a,b) && a < b; }
bool LTE(double a,double b) { return equals(a,b) || a < b; }
 
struct Point {
  double x,y,z;
  Point operator - ( const Point &p ) const { return (Point){x-p.x,y-p.y,z-p.z}; }
  bool operator < ( const Point &p ) const {
    return ( ( !equals(z,p.z) ) ? z > p.z : ( ( !equals(y,p.y) ) ? y < p.y : LT(x,p.x) ) );
  }
};

typedef pair<double,int> ii;

struct Edge{
  int to,cap; double cost; int rev;
  Edge(int to=0,int cap=0,double cost=0,int rev=0):to(to),cap(cap),cost(cost),rev(rev){}
};

const int MAX_V = 1100, IINF = INT_MAX;
int V;
vector<Edge> G[MAX_V];
double h[MAX_V],dist[MAX_V];
int prevv[MAX_V],preve[MAX_V];

inline void add_edge(int from,int to,int cap,double cost){
  G[from].push_back(Edge(to,cap,cost,G[to].size()));
  G[to].push_back(Edge(from,0,-cost,G[from].size()-1));
}

double min_cost_flow(int s,int t){
  double res = 0;
  while(1){
    fill(dist,dist+V,IINF);
    dist[s] = 0;
    bool update = true;
    while( update ){
      update = false;
      rep(v,V){
        if( dist[v] == IINF ) continue;
        rep(i,(int)G[v].size()){
          Edge &e = G[v][i];
          if( e.cap > 0 && !equals(dist[e.to],dist[v]+e.cost) && dist[e.to] > dist[v] + e.cost ){
            //cout << "update dist[" << e.to << "] = dist[" << v << "] + " << e.cost << endl;
            dist[e.to] = dist[v] + e.cost;
            //cout << dist[e.to] << " = " << dist[v] << " + " << e.cost << endl << endl;
            prevv[e.to] = v;
            preve[e.to] = i;
            update = true;
          }
        }
      }
    }

    if( equals(dist[t],IINF) ) break;

    int d = IINF;
    for(int v=t;v!=s;v=prevv[v]) {
      d = min(d,G[prevv[v]][preve[v]].cap);
    }
    if( d == 0 ) break;
    res += d * dist[t];
    for(int v=t;v!=s;v=prevv[v]){
      Edge &e = G[prevv[v]][preve[v]];
      e.cap -= d;
      G[v][e.rev].cap += d;
    }
  }
  return res;
}

int N,K;
Point ps[100];

const double MAX = 10000;

double getDist(Point p){ return sqrt(p.x*p.x+p.y*p.y+p.z*p.z); }

void compute(){
  map<int,int> counter;
  bool failed = false;
  rep(i,N) counter[(int)ps[i].z]++;
  for(map<int,int>::iterator it = counter.begin(); it != counter.end(); it++ ) {
    if( it->second > K ) { failed = true; break; }
  }
  if( failed ) { puts("-1"); return; }
  rep(i,N*4) G[i].clear();
  int source = N * 2;
  int sink = source + 2;
  V = sink +1;
  add_edge(source,source+1,K,0);
  rep(i,N) { 
    add_edge(source+1,i,1,0);
    add_edge(i,N+i,1,-MAX);
    add_edge(N+i,sink,1,0); 
  }

  rep(i,N) rep(j,N) if( i != j && ps[i].z > ps[j].z ){
    add_edge(N+i,j,1,getDist(ps[i]-ps[j]));
  }

  printf("%.10f\n",min_cost_flow(source,sink)+N*MAX);
}

int main(){
  while( cin >> N >> K, N|K ){
    rep(i,N) cin >> ps[i].x >> ps[i].y >> ps[i].z;
    compute();
  }
  return 0;
}

Measured memory_bytes: 1952
from bisect import bisect_left
import sys
sys.setrecursionlimit(10 ** 7)

n = int(input())
triangle = []
i = 1
while True:
	triangle.append(i * (i + 1) // 2)
	if triangle[-1] > n:
		break
	i += 1

ans = []

def search(i):
	global ans
	if i == 0:
		return ans
	else:
		ind = bisect_left(triangle, i)
		if i == triangle[ind]:
			ans += list(range(1, ind + 2))
			return ans
		else:
			ans.append(ind + 1)
			return search(i - (ind + 1))

print(*search(n), sep="\n")

Measured memory_bytes: 7668