akhauriyash/Code-Regression huggingface dataset:
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<vector<ll>>> vvvll;
typedef vector<bool> vb;
typedef vector<vector<bool>> vvb;
typedef vector<vector<vector<bool>>> vvvb;
typedef pair<ll, ll> pll;
typedef vector<pll> vpll;
typedef vector<vpll> vvpll;
typedef vector<double> vd;
typedef vector<vd> vdd;

#define FOR(i,x,y) for(ll i=(ll)x; i<(ll)y; ++i)
#define REP(i,y) FOR(i, 0, y)
#define RFOR(i,x,y) for(ll i=(ll)x; i>=(ll)y; --i)
#define RREP(i,x) RFOR(i, x, 0)
#define ALL(a) a.begin(), a.end()
#define pb push_back
#define debug_print(x...) cerr << "line " << __LINE__ << " : "; debug_print_in(x);

template <typename First>
void debug_print_in(First first){
  cerr << first << endl;
  return;
}

template <typename First, typename... Rest>
void debug_print_in(First first, Rest... rest){
  cerr << first << " ";
  debug_print_in(rest...);
  return;
}

void IN(void){
  return;
}

template <typename First, typename... Rest>
void IN(First& first, Rest&... rest){
  cin >> first;
  IN(rest...);
  return;
}

template <typename First>
void OUT(First first){
  cout << first << endl;
  return;
}

template <typename First, typename... Rest>
void OUT(First first, Rest... rest){
  cout << first << " ";
  OUT(rest...);
  return;
}

template<class t, class u> void chmax(t&a,u b){if(a<b)a=b;};
template<class t, class u> void chmin(t&a,u b){if(a>b)a=b;};
int popcount(int t){return __builtin_popcount(t);} //GCC
int popcount(ll t){return __builtin_popcountll(t);} //GCC

template <typename T>
void vec_print(vector<T> VEC){
  REP(i, VEC.size()){
    cerr << VEC[i] << " ";
  }
  cerr << endl;
};

template <typename T>
void mat_print(vector<vector<T> > MAT){
  REP(i,MAT.size()){
    REP(j,MAT[i].size()){
      cerr << MAT[i][j] << " ";
    }
    cerr << endl;
  }
};

constexpr int INF = (1<<30);
constexpr ll INFLL = 1LL<<62;
constexpr long double EPS = 1e-12;
constexpr ll MOD = (ll)((1E+9)+7);

int main(){
  cin.tie(0); // cut the cin and cout (default, std::flush is performed after std::cin)
  ios::sync_with_stdio(false); // cut the iostream and stdio (DON'T endl; BUT "\n";)

  string S, T;
  IN(S);
  IN(T);

  ll N = S.size();

  map<char, ll> mp1;
  map<char, ll> mp2;

  ll index1 = 1;
  ll index2 = 1;

  REP(i,N){
    if(mp1.find(S[i])==mp1.end()){
      mp1[S[i]] = index1++;
    }
    if(mp2.find(T[i])==mp2.end()){
      mp2[T[i]] = index2++;
    }
    if(mp1[S[i]] != mp2[T[i]]){
      OUT("No");
      return 0;
    }
  }

  OUT("Yes");

  return 0;
}

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

int main() {
  int N, t, pN, pt;
  cin>> N;
  t = 0;
  pN=N;
  while(N>0){
    pt=t;
  	t=N%10;
    t+=pt;
    N/=10;
  }
  if(pN%t == 0){
  	cout<<"Yes";
  }
  else{
    cout<<"No";
  }
  


}

Measured memory_bytes: 256
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

def solve():
    N, M = MI()

    uf = UnionFind(N)
    for i in range(M):
        a, b = MI1()
        uf.union(a, b)
    
    tmp = []
    # print(uf.roots())
    for r in uf.roots():
        # print(uf.size(r))
        tmp.append(uf.size(r))
    s = sorted(tmp, reverse=True)
    # print(s)
    if len(s) == 1:
        print(s[0])
    else:
        print(s[1] + s[0] - s[1])


if __name__ == '__main__':
    solve()



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

//------------------------------------------------------------------------------------------------
typedef long long ll;
typedef pair<ll, ll> pl;
typedef pair<ll, pl> pll;
typedef pair<int, int> pi;
typedef pair<int, pi> pii;
//-------------------------------------------------------------------------------------------------
#define PI acos(-1)
#define inf 1000000001
#define ninf -inf
#define pb push_back
#define mp make_pair
#define mod 1000000007
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int gcd(int a,int b){if(a==0)return b;else return gcd(b%a,a);}
int be(int a,int b){int ans=1;while(b){if(b&1){b--;ans*=a;ans%=mod;}b/=2;a*=a;a%=mod;}return ans;}
void fi(int &num){bool neg=false;num=0;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')break;ch=getchar();}if(ch=='-'){neg=true;ch=getchar();}while(ch>='0'&&ch<='9'){num=num*10+ch-'0';ch=getchar();}if(neg)num=-num;}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
int dp[100001];
int n,k;
signed main()
{
    for(int i=1;i<=100000;i++)dp[i]=inf;

    scanf("%d%d",&n,&k);
    int temp=n;
    while(n--)
    {int w,v;
    scanf("%d%d",&w,&v);
        for(int i=100000;i>=1;i--)
        {if((i-v)<0)break;
            if(dp[i]>(dp[i-v]+w))
                if((dp[i-v]+w)<=k)
                dp[i]=dp[i-v]+w;
        }
    }
    for(int i=100000;i>=0;i--)if(dp[i]!=inf&&dp[i]<=k){printf("%d\n",i);break;}
return 0;}



Measured memory_bytes: 640
n  = int(input())
a = list(map(int,(input().split())))
b = list(map(int,(input().split())))
s = sum(a)
for i in range(n):
	ans = a[i] - b[i]
	if ans>=0:
		a[i] = ans
	else:
		a[i] = 0
		ans = a[i+1] - abs(ans)
		if ans > 0:
			a[i+1] = ans
		else:
			a[i+1] = 0


print(s-sum(a))

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

int main(){
    //入力
    int N,K;

    cin >> N;
    cin >> K;

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

    //出力
    int ans=0;
    for(int i=0;i<N;i++){
        ans+=2*min(K-x.at(i),x.at(i));
    }

    cout << ans << endl;
}

Measured memory_bytes: 256
#include <iostream>

using namespace std;

int main () 
{
  long int n, k, min, max;
  long int ans = 0;
  const long int MOD = 1000000007;
  cin >> n >> k;
  for (long int i = k; i <= n + 1; ++i) {
  min = (i - 1) * i / 2;
  max = (n + 1) * n / 2 - (n - i) * (n - i + 1) / 2;
  ans += (max - min + 1); 
  ans %= MOD; }
  cout << ans;
 }


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

import sys
import numpy as np
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)

N, *A = map(int, read().split())

A = sorted(A)[::-1]
A = A[1:-N:2]

print(sum(A))


Measured memory_bytes: 40492
N,M,L,Q;
D[301][301];
i,j,k;
a,b,c;
main()
{
	scanf("%d%d%d",&N,&M,&L);
	for(i=1;i<=N;i++)for(j=i+1;j<=N;j++)D[i][j]=D[j][i]=1000000001;
	for(i=0;i<M;i++)
	{
		scanf("%d%d%d",&a,&b,&c);
		D[a][b]=D[b][a]=c;
	}
	for(k=1;k<=N;k++)for(i=1;i<=N;i++)for(j=1;j<=N;j++)
		if(D[i][j]>D[i][k]+D[k][j])D[i][j]=D[i][k]+D[k][j];
	for(i=1;i<=N;i++)for(j=1;j<=N;j++)
	{
		if(i!=j)D[i][j]=D[i][j]>L?1000000000:1;
	}
	for(k=1;k<=N;k++)for(i=1;i<=N;i++)for(j=1;j<=N;j++)
		if(D[i][j]>D[i][k]+D[k][j])D[i][j]=D[i][k]+D[k][j];
	scanf("%d",&Q);
	for(i=0;i<Q;i++)
	{
		scanf("%d%d",&a,&b);
		printf("%d\n",D[a][b]<1000000000?D[a][b]-1:-1);
	}
}

Measured memory_bytes: 768
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<map>
#include<set>
#include<cstring>
#include<string>
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define SZ(a) (int)((a).size())
using namespace std;
typedef long long ll;
typedef double db;
typedef pair <int, int> Pii;
typedef pair <ll, int> Pli;
typedef unsigned long long ull;
const double eps = 1e-8;
const ll infll = 0x7fffffffffffffff;
const int mod = (int)(1e9) + 7;
const int inf = 0x7fffffff;
const int maxn = (int)(2e5) + 7;
const int maxm = 300;

ll A, B, N;

int main() {
	
	scanf("%lld%lld%lld", &A, &B, &N);
	ll x = min(N, B - 1);
	printf("%lld", A * x / B - x / B * A);

	return 0;
}		

Measured memory_bytes: 3216
#include <bits/stdc++.h>
using namespace std;
using Graph = vector<vector<int>>;

Graph G;
vector<int> counter;
vector<bool> seen;

int N, Q;

void dfs(int v, int parent)
{
  seen.at(v) = true;
  counter.at(v) += counter.at(parent);
  int next_v;
  for (int i = 0; i < G.at(v).size(); i++)
  {
    next_v = G.at(v).at(i);
    if (seen.at(next_v))
    {
      continue;
    }
    dfs(next_v, v);
  }
}

int main()
{
  cin >> N >> Q;
  G.resize(N + 1);
  counter.resize(N + 1, 0);
  seen.resize(N + 1, false);
  int a, b;
  for (int i = 0; i < N - 1; i++)
  {
    cin >> a >> b;
    G.at(a).push_back(b);
    G.at(b).push_back(a);
  }
  int p, x;
  for (int j = 0; j < Q; j++)
  {
    cin >> p >> x;
    counter.at(p) += x;
  }
  dfs(1, 0);
  for (int i = 1; i <= N; i++)
  {
    if (i != 1)
    {
      cout << " ";
    }
    cout << counter.at(i);
  }
  cout << endl;
}

Measured memory_bytes: 23552
#include <algorithm>
#include <bitset>
#include <cctype>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

#define FOR(i,m,n) for(int i=(m);i<(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(v) (v).begin(),(v).end()

const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
/*----------------------------------------*/

int main() {
  cin.tie(0); ios::sync_with_stdio(false);
  // freopen("input.txt", "r", stdin);

  int n; cin >> n;
  cout << ((n==7||n==5||n==3)? "YES" : "NO") << "\n";
  return 0;
}


Measured memory_bytes: 256
use std::io::stdin;
use std::str::FromStr;
#[allow(dead_code, unused_mut)]
fn read<T: FromStr>() -> T {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    s.trim().parse().ok().expect("1")
}
#[allow(dead_code, unused_mut)]
fn read_vec<T: FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
        .map(|e| e.parse().ok().expect("2"))
        .collect()
}
#[allow(dead_code, unused_mut)]
fn read_two<T: FromStr>() -> (T, T) {
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let mut x = s.split_whitespace().map(|x| x.parse().ok().unwrap());
    (x.next().unwrap(), x.next().unwrap())
}
#[allow(dead_code, unused_mut)]
fn read_three<T: FromStr>() -> (T, T, T) {
    let mut s = String::new();
    stdin().read_line(&mut s).unwrap();
    let mut x = s.split_whitespace().map(|x| x.parse().ok().unwrap());
    (x.next().unwrap(), x.next().unwrap(), x.next().unwrap())
}
fn main() {
    let (mut a, b) = read_two::<String>();
    a.push_str(&b);
    let a: i32 = a.parse().ok().unwrap();
    let x = (a as f64).sqrt();
    if a == (x as i32).pow(2) {
        println!("Yes");
    } else {
        println!("No");
    }
}

Measured memory_bytes: 4352
/*
     bitwise ^_^
*/

#include<bits/stdc++.h>
using namespace std;
const int mxn = 2*1e3+5;
int ar[mxn] , n;
int sum;
bitset< mxn*mxn > b;

int main()
{
	cin>>n;
	sum  = 0;
	b.set(0);
	for(int i  = 1;i <= n;i++)
	{
		cin>>ar[i];
		sum +=ar[i];
		b = b|(b<<ar[i]);
	}
	for(int i = (sum+1)/2; i <= sum; i++)
	{
		if(b[i])
		{
			cout<<i<<endl;
			return 0;
		}
	}
	return 0;
}



Measured memory_bytes: 2304
// created_by  Rishi_Mohan

#include<bits/stdc++.h>

#define    ll           long long
#define    db1(x)       cout<<#x<<"="<<x<<'\n'
#define    db2(x,y)     cout<<#x<<"="<<x<<","<<#y<<"="<<y<<'\n'
#define    db3(x,y,z)   cout<<#x<<"="<<x<<","<<#y<<"="<<y<<","<<#z<<"="<<z<<'\n'

using namespace std;

void solve()
{
    int a,b;
    cin >> a >>b;
    cout << a*b << endl;
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    solve();
}


Measured memory_bytes: 3648
#include<stdio.h>
#include<string.h>
#define N 36

typedef struct
{
  char pat;
  int value;
}card;


int main()
{
  int i,j,n,mini,a,b,jud;
  card C[N],A[N],B[N],temp;

  scanf("%d",&n);

  for(i=0;i<n;i++)
    {
      scanf(" %c%d",&C[i].pat,&C[i].value);
      A[i] = B[i] = C[i];
    }

  for(i=0;i<n;i++)               //Bubble
    {    
      for(j=n-1;j>=i+1;j--)
	{     
	  if(A[j].value < A[j-1].value)
	    {
	      temp = A[j];
	      A[j] = A[j-1];
	      A[j-1] = temp;
	    }
	}
    }
  

   for(i=0;i<n;i++)
    {
      printf("%c%d",A[i].pat,A[i].value);
      if(i!=n-1)printf(" ");
      else printf("\n");
    }

      jud=0;
   for(i=0;i<n;i++)
     {
       for(j=i+1;j<n;j++)
	 {
	   for(a=0;a<n;a++)
	     {
	       for(b=a+1;b<n;b++)
		 {
		   if(A[i].value==A[j].value && (A[i].value==C[b].value && A[i].pat==C[b].pat) && (A[j].value==C[a].value && A[j].pat== C[a].pat))jud=1;
		 }
	     }
	 }
     }
   if(jud == 0)printf("Stable\n");
   else printf("Not stable\n");


  for(i=0;i<n;i++)               //Selection
    {
      mini = i;
      for(j=i;j<n;j++)
	{
	  if(B[j].value < B[mini].value)
	    {
	      mini = j;
	    }
	}
      temp = B[i];
      B[i] = B[mini];
      B[mini] = temp;
    }
  
    for(i=0;i<n;i++)
    {
      printf("%c%d",B[i].pat,B[i].value);
      if(i!=n-1)printf(" ");
      else printf("\n");
    }

        jud=0;
   for(i=0;i<n;i++)
     {
       for(j=i+1;j<n;j++)
	 {
	   for(a=0;a<n;a++)
	     {
	       for(b=a+1;b<n;b++)
		 {
		   if(B[i].value == B[j].value &&( B[i].value == C[b].value && B[i].pat == C[b].pat )&& (B[j].value == C[a].value &&B[j].pat==C[a].pat))jud=1;
		 }
	     }
	 }
     }
   if(jud == 0)printf("Stable\n");
   else printf("Not stable\n");


   
  return 0;
}










Measured memory_bytes: 2104
#include<bits/stdc++.h>
using namespace std;
 
int main(){
    int n;
    cin>>n;
    string s;
    cin>>s;
 
    int ans=1e9;
 
    int b[n+1]={},w[n+1]={};
    for(int i=0;i<n;i++){
        b[i+1]=b[i];
        w[i+1]=w[i];
        if(s[i]=='.') w[i+1]++;
        else b[i+1]++;
    }
    for(int i=0;i<=n;i++){
        int r=0;
        //cerr<<w[i]<<" "<<b[n-i]<<endl;
        r=w[n]-w[i]+b[i];
        ans=min(r,ans);
    }
    cout<<ans<<endl;
}

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

int n,d,hed[2010],cnt,k,fa[2010],dep[2010],ans=2e9,book[2010];
struct node
{
	int from,to,next;
}a[100010];
inline void add(int from,int to)
{
	a[++cnt].to=to;
	a[cnt].from=from;
	a[cnt].next=hed[from];
	hed[from]=cnt;
}
inline void dfs(int x)
{
	for(int i=hed[x];i;i=a[i].next)
	{
		int y=a[i].to;
//		cout<<y<<endl;
		if(fa[x]==y||book[y])
		continue;
//		cout<<y<<" "<<dep[y]<<endl;
		dep[y]=dep[x]+1;
		fa[y]=x;
		dfs(y);
	}
}
int main()
{
	scanf("%d%d",&n,&k);
	cnt=1;
	for(int i=1;i<=n-1;++i)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		add(x,y);
		add(y,x);
	}
/*	dfs(1);
	int mx=0,ji=1;
	for(int i=1;i<=n;++i)
	{
		if(dep[i]>mx)
		{
			mx=dep[i];
			ji=i;
		}
	}
	memset(fa,0,sizeof(fa));
	memset(dep,0,sizeof(dep));
	dfs(ji);
	for(int i=1;i<=n;++i)
	d=max(d,dep[i]);*/
//	cout<<d<<endl;
	if(k%2)
	{
		for(int i=2;i<=cnt;i++)
		{
			memset(fa,0,sizeof(fa));
			memset(dep,0,sizeof(dep));
			book[a[i].to]=1;
			dfs(a[i].from);
			int ji=0;
//			cout<<a[i].from<<" "<<a[i].to<<endl;
//			for(int i=1;i<=n;++i)
//			cout<<dep[i]<<" ";
//			cout<<endl;
			for(int j=1;j<=n;++j)
			{
				if(dep[j]>k/2)
				++ji;
			}
			memset(fa,0,sizeof(fa));
			memset(dep,0,sizeof(dep));
			book[a[i].from]=1;
			book[a[i].to]=0;
			dfs(a[i].to);
			for(int j=1;j<=n;++j)
			{
				if(dep[j]>k/2)
				++ji;
			}
			book[a[i].from]=0;
			ans=min(ans,ji);
		}
	}
	else
	{
		for(int i=1;i<=n;++i)
		{
			memset(fa,0,sizeof(fa));
			memset(dep,0,sizeof(dep));
			dfs(i);
			int ji=0;
			for(int j=1;j<=n;++j)
			{
				if(dep[j]>k/2)
				++ji;
			}
			ans=min(ans,ji);
		}
	}
	printf("%d\n",ans);
	return 0;
}

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

int main()
{
	int n,cnt=0;
	cin >> n;
	
	for (int i = 1; i <= n/2; ++i)
	{
		for (int j = i+1; j <= (n+1)/2; ++j)
		{
			cnt++;
			break;
		}
	}
	
	cout << cnt << endl;
	
	return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<vector>
#include<string>
#include<sstream>
#include<cmath>
#include<numeric>
#include<map>
using namespace std;


int main(void) {

  int n;
  cin >> n;
  vector<int> a(n);
  for(int i=0; i<n; i++) cin >> a[i];

  int mx = *max_element(a.begin(), a.end());
  int mn = *min_element(a.begin(), a.end());
  cout << mx - mn << endl;

  return 0;
}


Measured memory_bytes: 256
from bisect import *
def solve():
  ans = 0
  N, D, A = map(int, input().split())
  B = [list(map(int, input().split())) for _ in range(N)]
  B.sort()
  lasts = [0]*(N+1)
  now = 0
  for i,((x,h),l) in enumerate(zip(B,lasts)):
    now -= l
    atack = max(0,-(-(h-now)//A))
    ans += atack
    damage = atack*A
    now += damage
    last = x+2*D
    ind = bisect_right(B,[last+1,0])
    lasts[ind] += damage
  return ans
print(solve())


Measured memory_bytes: 53316
#include <iostream>
#include <algorithm>
#include <stdio.h>

using namespace std;

int main(){
    int a,b;
    scanf("%d %d",&a,&b);
    if(a<1||a>9||b<1||b>9){
        printf("%d\n",-1);
    }else{
        printf("%d\n",a*b);
    }
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i, n) for(ll i=0;i<n;i++)
using namespace std;
template<class T>bool chmax(T &a, const T &b) { if (b>a) { 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; }
//const long long INF = 2LL << 60;
using ll = long long;
using P = pair<ll, ll>;
int main(int argc, char const *argv[]){
    int a;
    rep(i,5){
        cin >> a;
        if(a==0){
            cout << i+1 << endl;
        }
    }
    return 0;
}




Measured memory_bytes: 3568
//{{{
#include<algorithm>
#include<cmath>
#include<deque>
#include<fstream>
#include<iomanip>
#include<iostream>
#include<map>
#include<numeric>
#include<queue>
#include<random>
#include<set>
#include<sstream>
#include<sys/time.h>
#include<unordered_map>
#include<unordered_set>
#include<vector>
using ll = long long;
enum : int { M = (int)1e9 + 7 };
enum : ll { MLL = (ll)1e18L + 9 };
using namespace std;
#ifdef LOCAL
#include"rprint2.hpp"
#else
#define FUNC(name) template <ostream& out = cout, class... T> void name(T&&...){ }
FUNC(printde) FUNC(printdbe) FUNC(printdwe) FUNC(printdu);
#endif
template <template <class T, class = std::allocator<T>> class V, class E>
istream& operator >> (istream& in, V<E>& v){ for(auto& e : v){ in >> e; } return in; }
//}}}

int main(){
    cin.tie(0); ios::sync_with_stdio(false);
    int n; cin >> n;
    vector<int> as(n + 1); cin >> as;
    vector<int> bs(n); cin >> bs;
    ll ans = 0;
    for(int i = 0; i < n; i++){
        int num = min(as[i], bs[i]);
        ans += num;
        as[i] -= num;
        bs[i] -= num;
        num = min(as[i + 1], bs[i]);
        ans += num;
        as[i + 1] -= num;
        bs[i] -= num;
    }
    cout << ans << '\n';
}


Measured memory_bytes: 1024
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
#define mod 1000000007
#define exp pow(10,-9)
#define F first
#define S second
#define PB push_back 
#define MP make_pair
#define time ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define lowercase(str) transform(str.begin(), str.end(), str.begin(), ::tolower);
#define uppercase(str) transform(str.begin(), str.end(), str.begin(), ::toupper);
main()
{
	int x,n;
	cin>>x>>n;
	int arr[n];
	for(int i=0;i<n;i++)
		cin>>arr[i];
		
	sort(arr,arr+n);
	
	int mi = 1000,ans;
	
	if(!binary_search(arr,arr+n,x))
		cout<<x<<"\n";
	else
	{
		for(int i=-4;i<=500;i++)
		{
			if(!binary_search(arr,arr+n,i))
			{
				if(abs(x-i) < mi)
				{
					mi = abs(x-i);
					ans = i;
				}
			}
		}
		cout<<ans<<"\n";
	}

}

Measured memory_bytes: 3636
#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "string"
#include "map"
//#include "unordered_map"
//#include "unordered_set"
#include "iomanip"
#include "cmath"
//#include "random"
#include "bitset"
#include "cstdio"
#include "numeric"
#include "cassert"
#include "functional"

using namespace std;

//constexpr long long int MOD = 1000000007;
const int MOD = 1000000007;
//constexpr int MOD = 998244353;
//constexpr long long int MOD = 998244353;

//const double EPS = 1e-8;

//int N, M, K, H, W, L, R;
long long int N, M, K, H, W, L, R;

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

	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		cin >> L >> R >> K;
	}
	cin >> K;
	for (int i = 0; i < K; i++)cout << -1 << endl;
}

Measured memory_bytes: 384
#pragma gcc optimize("Ofast")
#include<bits/stdc++.h>
using namespace std;
#define FOR(i,r,n) for(ll i=(ll)(r);i<(ll)(n);++i)
#define RFOR(i,r,n) for(ll i=(ll)(n-1);i>=r;--i)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,0,n)
#define ALL(x) x.begin(),x.end()
#define RALL(x) x.rbegin(),x.rend()
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define pb(n) push_back(n)
#define endl '\n'
#define debug(x) cout << #x << " = " << (x) << endl
#define IN(n) cin >> n
#define IN2(a,b) cin >> a >> b
#define IN3(a,b,c) cin >> a >> b >> c
#define VIN(V) for(int ii = 0; ii < (V).size(); ii++) {cin >> (V).at(ii);}
#define OUT(n) cout << n << endl
#define OUT2(n1,n2) cout << n1 << " " << n2 << endl
#define OUT3(n1,n2,n3) cout << n1 << " " << n2 << " " << n3 << endl
#define VOUT(V) REP(ii,(V).size()){cout << (V)[ii] << " ";} cout<<endl;
#define VOUT2(V) REP(jj,(V).size()){VOUT(V[jj])}
typedef long long int ll;
typedef vector<ll> vi;
typedef vector<vi > vvi;
typedef vector<pair<ll, ll> > vp;
typedef vector<string> vs;
typedef vector<char> vc;
typedef list<ll> lst;
typedef pair<ll, ll> P;
const long long INF = numeric_limits<ll>::max();
const long long MOD = 1000000007;
const long double PI = 3.1415926;
template <class T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <class T> T &chmax(T &a, const T &b) { return a = max(a, b); }
ll n, m, k, ans, sum, cnt = 0; string s; char c; bool flg;

int main(){
  cin.tie(0);ios::sync_with_stdio(false);
  IN(s);
  SORT(s);
  if (s[0]==s[1] && s[1]!=s[2] && s[2]==s[3]) {
    OUT("Yes");
  } else {
    OUT("No");
  }
}


Measured memory_bytes: 384
/* Author - thiolhub */

#include <bits/stdc++.h>

using namespace std;

#define ll              long long int
#define ld              long double
#define db              double
#define pi              3.1415926535897932384626
#define PI              acos(-1.0)
#define endl            "\n"
#define mod             1000000007
#define mk              make_pair
#define pb              push_back
#define pii             pair<int,int>
#define vi              vector<int>
#define mii             map<int,int>
#define pqb             priority_queue<int>
#define pqs             priority_queue<int,vi,greater<int> >
#define setbits(x)      __builtin_popcountll(x)
#define zrobits(x)      __builtin_ctzll(x)
#define ps(x,y)         fixed<<setprecision(y)<<x
#define w(t)            ll t; cin>>t; while(t--)
#define sc(a)	        scanf("%lld",&a);
#define pr(a)	        printf("%lld\n",a)
#define rep(i,a,n)		for(ll i=a;i<n;i++)
#define m(a)		    memset(a,0,sizeof(a))
#define FastIO          ios_base::sync_with_stdio(0);cin.tie(0),cout.tie(0)
#define min3(a,b,c)     min(a,min(b,c))



int main(){ FastIO;

int n,m,i;cin>>n>>m;
unordered_map<int,int> h;
for(int j=0;j<m;j++)
{
	int d;cin>>d;
	for(i=0;i<d;i++)
	{
		int a;cin>>a;
		h[a]=1;
	}
}
int res=0;
for(i=1;i<n+1;i++){
	if(!h[i]){
		res++;
	}
}
cout<<res;


return 0;
}

Measured memory_bytes: 3660
#include<iostream>
#include<cstdio>

const int MAXN=1e5+5;

int n;
int a[MAXN<<1];
bool jud(int k)
{
	for(int i=0;i<n;i++)
	{
		if(a[n+i]<k&&a[n+i+1]<k) return false;
		if(a[n-i]<k&&a[n-i-1]<k) return false;
		if(a[n+i]>=k&&a[n+i+1]>=k) return true;
		if(a[n-i]>=k&&a[n-i-1]>=k) return true;
	}
	return a[1]>=k;
}

int main()
{
	int i;scanf("%d",&n);
	for(i=1;i<n<<1;i++) scanf("%d",a+i);
	int l=0,r=n<<1;
	while(l<=r)
	{
		int mid=(l+r)>>1;
		if(jud(mid)) l=mid+1;
		else r=mid-1;
	}
	printf("%d",r);
	return 0;
}


Measured memory_bytes: 1024
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Rooted Tree for Misawa-san
 */
public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line;
		String[] words;

		Node tree1, tree2, tree;
		tree1 = Node.parseNode(br.readLine());
		tree2 = Node.parseNode(br.readLine());
		tree = Node.merge(tree1, tree2);

		System.out.println(tree.toString());

	} //end main
}

class Node {
	Node parent, left, right;
	int value = -1;

	public static Node parseNode(String str) {

		if (str.isEmpty()) {
			return null;
		}

		Node node = new Node();

		Deque<Character> stack = new ArrayDeque<>();

		int i, j, v = 0;
		for (i = 0; i < str.length(); i++) {
			char c = str.charAt(i);
			switch (c) {
				case '(':
					stack.push(c);
					for (j = i + 1; j < str.length(); j++) {
						char _c = str.charAt(j);
						if (_c == '(') {
							stack.push(_c);
						}
						if (_c == ')') {
							stack.pop();
						}
						if (stack.isEmpty()) {
							if (node.value < 0) {
								node.left = Node.parseNode(str.substring(i + 1, j));
							} else {
								node.right = Node.parseNode(str.substring(i + 1, j));
							}
							i = j;
							break;
						}
					}
					break;
				case ')':
					break;
				case '[':
					break;
				case ']':
					node.value = v;
					break;
				default:
					v *= 10;
					v += c - '0';
			}
		}

		return node;
	}

	public static Node merge(Node t1, Node t2) {

		if (t1 == null || t2 == null) {
			return null;
		}

		Node node = new Node();

		node.value = t1.value + t2.value;
		node.left = Node.merge(t1.left, t2.left);
		node.right = Node.merge(t1.right, t2.right);

		return node;
	}

	public String toString() {

		String ls = "";
		String rs = "";

		if (left != null) ls = left.toString();
		if (right != null) rs = right.toString();

		return String.format("(%s)[%d](%s)", ls, value, rs);
	}
}

Measured memory_bytes: 29848
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < (n); i++)
#define RREP(i, n) for (int i = (n); i >= 0; i--)
#define FOR(i, m, n) for (int i = (m); i < (n); i++)
#define ALL(obj) begin(obj), end(obj)
using namespace std;
using ll = long long;
using ull = unsigned long long;

const int INF = 2100100100;
const int MOD = 1e9 + 7;

// 多次元 vector 生成
template <class T> vector<T> make_vec(size_t a) { return vector<T>(a); }
template <class T, class... Ts> auto make_vec(size_t a, Ts... ts) {
    return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}
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;
}
int main() {
    // cin.tie(0);
    // ios::sync_with_stdio(false);

    int N;
    cin >> N;
    vector<string> s(N);
    REP(i, N) {
        cin >> s.at(i);
        sort(ALL(s[i]));
    }
    sort(ALL(s));

    // REP(i, N) { cout << s[i] << endl; }
    ll ans = 0;
    ll now = 1;
    REP(i, N - 1) {
        if (s[i] == s[i + 1]) {
            now++;
        } else {
            if (now > 1) {
                ans += now * (now - 1) / 2;
            }
            now = 1;
        }
    }
    if (now > 1) {
        ans += now * (now - 1) / 2;
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 7296
#include<bits/stdc++.h>
#define ll long long 
#define ull unsigned long long
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep1(i,n) for (int i = 1; i <= (n); ++i)
#define repr(i,n) for (int i = n; i >= 0; --i)
#define P pair<int, int>
#define ALL(x) (x).begin(),(x).end()
const int INF = 1e9;
using namespace std;

void search(int x, int y) {
	
}

void dfs(int x, int y) {
	
}

int solve() {
	
}

int main() {
	unsigned int x;
	cin >> x;
	bitset<32>b(x);
	cout << b << endl;
	cout << (~b) << endl;
	cout << (b<<1) << endl;
	cout << (b>>1) << endl;
}


Measured memory_bytes: 3152
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
N,A,B,C,D = map(int,input().split())
s = list(input())
ok = False

# AC間、BD間、に連続した岩がなければ良い
#print (s)
for i in range(A-1,C):
#    print (s[i-1:i+1])
    if s[i-1:i+1] == ["#","#"]:
        print ("No")
        exit ()

#print (s)
for i in range(B-1,D):
#    print (s[i-1:i+1])
    if s[i-1:i+1] == ["#","#"]:
        print ("No")
        exit ()


# C > D の場合
# BD間に連続した3つの空きがあれば良い
if C < D:
    ok = True
else:
#    print (s)
    for i in range(B-1,D):
#        print (s[i-1:i+2])
        if s[i-1:i+2] == [".",".","."]:
            ok = True
            break

if ok:
    print ("Yes")
else:
    print ("No")


Measured memory_bytes: 4916
#include<iostream>
#include<math.h>
#include<cstring>
#include<vector>
#include<map>

typedef long long ll;

using namespace std;

#define rep(i,n) for(i=0;i<n;i++)
int main(){
    ll i,j;
    ll a,b,c;
    ll x,y;
    cin>>a>>b>>c>>x>>y;
    ll ma=max(x,y);
    ll ans=2*ma*c;
    ll sa=0;
    ll big=0;
    if(x>y){
        sa=x-y;
        big=a;
    }else{
        sa=y-x;
        big=b;
    }
    ll ans1=0;
    ll temp1=0;
    for(i=0;i<=sa;i++){
        temp1=ans-2*i*c+i*big;
        if(ans>temp1){
            ans1=temp1;
        }
    }
    ll ans2=0;
    for(j=0;j<=min(x,y);j++){
        ll temp=temp1-2*j*c+j*(a+b);
        if(temp<ans){
            ans2=temp;
        }
    }
    if(ans1==0 && ans2!=0){
        cout<<ans2<<endl;
        return 0;
    }else if(ans2==0 && ans1!=0){
        cout<<ans1<<endl;
        return 0;
    }
    if(ans>ans1 && ans2>ans1){
        ans=ans1;
    }else if(ans>ans2 && ans1>ans2){
        ans=ans2;
    }else{
        ;
    }
    cout<<ans<<endl;
}



Measured memory_bytes: 3552
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <cstdio>
#include <cmath>
#include <tuple>
#include <iomanip>
#include <numeric>
#include <unordered_map>
#include <sstream>   

using namespace std;
#define i64  long long

#define I32_MAX 2147483647
#define I64_MAX 9223372036854775807


void solve(void)
{ 

  int N;

  while(true)
  {
    cin>>N;
    if(N == 0)break;

    vector<double> vec(N,0);

    for (int i = 0; i < N; i++)
    {
      cin>>vec[i];  
    }
    

    double avg = 0;

    for (int i = 0; i < N; i++)
    {
      avg += vec[i];
    }
    avg /= N;
    

    double variance = 0;
    for (int i = 0; i < N; i++)
    {
      variance += pow(vec[i]-avg,2);

    }
    variance /=double(N);
    cout<<fixed;
    cout<<setprecision(6);

    cout<<sqrt(variance)<<endl;
    
  }

  return;
}

int main(int argc, const char *argv[])
{

  solve();

  return 0;
}



Measured memory_bytes: 3268
from copy import copy
from collections import defaultdict  

def bubble_sort(collection):
    collection = copy(collection)
    for i in range(len(collection)):
        for j in range(len(collection)-1, i, -1):
            if collection[j] < collection[j-1]:
                collection[j], collection[j-1] = collection[j-1], collection[j]
    return collection
    
def selection_sort(collection):
    collection = copy(collection)
    for i in range(len(collection)):
        mini = i
        for j in range(i, len(collection)):
            if collection[j] < collection[mini]:
                mini = j
        collection[i], collection[mini] = collection[mini], collection[i]
        
    return collection
    
def print_cards(cards):
    for card in cards[:-1]:
        print(card, end=' ')
    print(cards[-1])

def find_card_order(cards):
    duplicate_numbers = defaultdict(list)
    for card in cards:
        duplicate_numbers[card.number].append(card.suit)
    duplicate_numbers = {k: v for k, v in duplicate_numbers.items() if len(v) >= 2}
    return duplicate_numbers



class Card:
    def __init__(self, card):
        self._suit = card[0]
        self._number = int(card[1])
    
    def __str__(self):
        return self.card
    
    def __lt__(self, other):
        return self._number < other._number
        
    @property
    def card(self):
        return self._suit + str(self._number)
    
    @property
    def number(self):
        return self._number
    @property
    def suit(self):
        return self._suit
        
nums_card = int(input())
cards = list(map(Card, input().split()))
duplicate_cards =  find_card_order(cards)
bubble_sorted = bubble_sort(cards)
selection_sorted = selection_sort(cards)


print_cards(bubble_sorted)

stable = 'Stable'
for k, v in duplicate_cards.items():
    sorted_order = [card.suit for card in bubble_sorted if card.number == k]
    if duplicate_cards[k] != sorted_order:
        stable = 'Not stable'
print(stable)

print_cards(selection_sorted)
stable = 'Stable'
for k, v in duplicate_cards.items():
    sorted_order = [card.suit for card in selection_sorted if card.number == k]
    if duplicate_cards[k] != sorted_order:
        stable = 'Not stable'
print(stable)


Measured memory_bytes: 6360
object Main{
  def main(args: Array[String]){
      val input=io.Source.stdin.getLines().mkString("\n")
      println(solve(input).toString.trim());
  }
  def solve(input:String):Int ={
    val g = input.split("\n")(1).split(" ").map(_ .toInt)
    var ret = 0
    for( i <- 1 until g.size-1){
    	if( ( g(i-1) < g(i) && g(i) <= g(i+1) )|| ( g(i-1) >= g(i) && g(i) > g(i+1) ) )
        {
         ret +=1
        }
    }
    ret
  }
}

Measured memory_bytes: 27340
// C++ program to find the longest repeated 
// non-overlapping substring 
#include<bits/stdc++.h>
using namespace std; 
#define int long long
// Returns the longest repeating non-overlapping 
// substring in str 
int longestRepeatedSubstring(string str) 
{ 
	int n = str.length(); 
	int LCSRe[n+1][n+1]; 

	// Setting all to 0 
	memset(LCSRe, 0, sizeof(LCSRe)); 

	string res; // To store result 
	int res_length = 0; // To store length of result 

	// building table in bottom-up manner 
	int i, index = 0; 
	for (i=1; i<=n; i++) 
	{ 
		for (int j=i+1; j<=n; j++) 
		{ 
			// (j-i) > LCSRe[i-1][j-1] to remove 
			// overlapping 
			if (str[i-1] == str[j-1] && 
				LCSRe[i-1][j-1] < (j - i)) 
			{ 
				LCSRe[i][j] = LCSRe[i-1][j-1] + 1; 

				// updating maximum length of the 
				// substring and updating the finishing 
				// index of the suffix 
				if (LCSRe[i][j] > res_length) 
				{ 
					res_length = LCSRe[i][j]; 
					index = max(i, index); 
				} 
			} 
			else
				LCSRe[i][j] = 0; 
		} 
	} 

	// If we have non-empty result, then insert all 
	// characters from first character to last 
	// character of string 
	if (res_length > 0) 
		for (i = index - res_length + 1; i <= index; i++) 
			res.push_back(str[i-1]); 

	return res.size(); 
} 

// Driver program to test the above function 
int32_t main() 
{ 
  
  int n;
  cin>>n;
	string str;
  cin>>str;
	cout << longestRepeatedSubstring(str); 
	return 0; 
} 


Measured memory_bytes: 195712
#include <iostream>
#include <math.h>
#include <string>
#include <algorithm>
#include <ctype.h>
#include <vector>
#include <numeric>
using namespace std;

#define ll long long int
#define rep(i, a, n) for (int i = a; i < n; i++)
#define INF 1e9
#define LINF 1e17
#define MOD (int)(1e9 + 7)
#define pi 3.141592653589
#define pii pair<int, int>
#define vi vector<int>
#define vll vector<ll>
#define ALL(a) (a).begin(), (a).end()
#define sort_v(a) sort(a.begin(), a.end())
#define fi first
#define se second

void print(bool a)
{
    if (a == true)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
}

ll gcdll(ll a, ll b)
{
    while (1)
    {
        if (a < b)
            swap(a, b);
        if (b == 0)
            break;
        a %= b;
    }
    return a;
}

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int main()
{
    int a, b, c, n;
    cin >> a >> b >> c;
    //string s;
    //cin >> s;

    rep(i, 0, 10)
    {
        c = a * c - b;
        cout << c << endl;
    }
}


Measured memory_bytes: 256
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

	public static void main(String[] args) throws IOException{

		List<Integer> l = new ArrayList<Integer>();
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			String inputNum = br.readLine();
			if (inputNum.equals("0")) {
				break;
			}

			l.add(Integer.parseInt(inputNum));
		}

		for (int i = 1; i <= l.size(); i++) {

			System.out.println("Case " + i + ": " + l.get(i-1));
		}


	}

}

Measured memory_bytes: 27436
#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip


from collections import deque


def main():
    n, d, a = map(int, input().split())
    x, h = [0] * n, [0] * n
    for i in range(n):
        x[i], h[i] = map(int, input().split())

    order = sorted(range(n), key=lambda idx: x[idx])
    res = 0
    sub = 0
    bounds = deque()
    for idx in order:
        while bounds and x[idx] > bounds[0][0]:
            bound, count = bounds.popleft()
            sub -= count
        h[idx] -= sub
        if h[idx] > 0:
            bound = x[idx] + 2 * d
            count = (h[idx] + a - 1) // a
            sub += count * a
            bounds.append((bound, a * count))
            res += count

    print(res)


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


Measured memory_bytes: 69740
/**Lucky Boy**/
#include <bits/stdc++.h>
#define FOR(i, a, b) for (long long i = (a); i <= (b); ++i)
#define FORD(i, a, b) for (long long i = (a); i >= (b); --i)
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define maxc 1000000007
#define maxn 1003
#define maxm 500005
#define pii pair <int,int>
#define Task ""
template <typename T> inline void read(T &x){char c;bool nega=0;while((!isdigit(c=getchar()))&&(c!='-'));if(c=='-'){nega=1;c=getchar();}x=c-48;while(isdigit(c=getchar())) x=x*10+c-48;if(nega) x=-x;}
template <typename T> inline void writep(T x){if(x>9) writep(x/10);putchar(x%10+48);}
template <typename T> inline void write(T x){if(x<0){putchar('-');x=-x;}writep(x);putchar(' ');}
template <typename T> inline void writeln(T x){write(x);putchar('\n');}
using namespace std;
string s;
int ans = maxc,cur;
int main()
{
    ios_base::sync_with_stdio(NULL);cin.tie(NULL);cout.tie(NULL);
    //freopen(Task".inp", "r",stdin);
    //freopen(Task".out", "w",stdout);
    cin >> s;
    FOR(i,0,1) cur = cur * 10 + (s[i] - '0');
    FOR(i,2,s.size() - 1)
        {
            cur = 10 * cur + s[i] - '0';
            ans = min(ans,abs(cur - 753));
            cur %= 100;
        }
    cout << ans;
    return 0;
}


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

typedef long long ll;
#define REP(i, n, m) for(int i = n; i < m; i++)
#define REPR(i, n, m) for(int i = n; i >= m; i--)
#define LREP(i, n, m) for(ll i = n; i < m; i++)
#define LREPR(i, n, m) for(ll i = n; i >= m; i--)

#define P pair<int, int >


const int INF = 1e9 + 1;
const int MOD = 1e9 + 7;



//---functions---//
int gcd(int a, int b){
    if(a < b) swap(a, b);
    return b?gcd(b, a%b):a;
}

int s2i(string num){stringstream ss; ss << num << flush; int n; ss >> n; return n;}
string i2s(int n){stringstream ss; ss << n << flush; return ss.str();}

bool firstCompare(const P& firstElof, const P& secondElof){
    return firstElof.first < secondElof.first;
}
bool secondCompare(const P& firstElof, const P& secondElof){
    return firstElof.second < secondElof.second;
}
//---------------//

int N;
int A, B, C;
int main(){
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);

    cin >> N >> A >> B >> C;

    int l[N];
    REP(i, 0, N) cin >> l[i];
    int ans = INF;
    int digits[N+1];
    int len[3] = {0, 0, 0};
    digits[0] = 4;
    REP(i, 1, N+1) digits[i] = digits[i-1] * 4;
    int tmp;
    int tmp_ans;
    bool flag;
    REP(i, 0, digits[N]){
        tmp_ans = 0;
        len[0] = 0; len[1] = 0; len[2] = 0;
        REP(j, 1, N + 1){
            tmp = i / digits[j-1] % 4;
            if(tmp == 3){
                continue;
            }else{
                if(len[tmp] > 0) tmp_ans += 10;
                len[tmp] += l[j-1];
            }
        }

        flag = true;
        REP(j, 0, 3){
            if(len[j] == 0){
                flag = false;
            }
        }
        tmp_ans += abs(len[0] - A);
        tmp_ans += abs(len[1] - B);
        tmp_ans += abs(len[2] - C);

        if(flag){
            ans = min(ans, tmp_ans);
        }
    }

    cout << ans << endl;
}


Measured memory_bytes: 256
n = int(input())
dp = [[0 for _ in range(3)]for _ in range(n)]
cost = []
for i in range(n):
    cost.append(list(map(int,input().split())))
ans = 0
dp[0][0] = cost[0][0]
dp[0][1] = cost[0][1]
dp[0][2] = cost[0][2]
if n == 1:
    print(max(dp[0]))
    exit()
for i in range(n-1):
    for j in range(3):
        for k in range(3):
            if j != k:
                dp[i+1][k] = max(dp[i+1][k],dp[i][j]+cost[i+1][k])
if dp[-1][0] < dp[-1][1]:
    if dp[-1][1] < dp[-1][2]:
        print(dp[-1][2])
    else:
        print(dp[-1][1])
else:
    if dp[-1][0] < dp[-1][2]:
        print(dp[-1][2])
    else:
        print(dp[-1][0])

Measured memory_bytes: 51932
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        List<int> a = new List<int>();
        for (int i = 0; i < n; i++)
        {
            a.Add(int.Parse(Console.ReadLine()));
        }
        a.Sort();

        List<int> ans = new List<int>();
        int cnt = 0;
        ans.Add(a[0]);
        for (int i = 1; i < a.Count; i++)
        {
            switch (i % 4)
            {
                case 1:
                    ans.Add(a[a.Count - 1 - cnt]);
                    break;
                case 2:
                    ans.Insert(0, a[a.Count - 2 - cnt]);
                    break;
                case 3:
                    ans.Add(a[cnt + 1]);
                    break;
                case 0:
                    ans.Insert(0, a[cnt + 2]);
                    cnt += 2;
                    break;
            }
        }

        List<int> ans2 = new List<int>();
        cnt = 0;
        ans2.Add(a[a.Count - 1]);
        for (int i = 1; i < a.Count; i++)
        {
            switch (i % 4)
            {
                case 1:
                    ans2.Add(a[cnt]);
                    break;
                case 2:
                    ans2.Insert(0, a[cnt + 1]);
                    break;
                case 3:
                    ans2.Add(a[a.Count - 2 - cnt]);
                    break;
                case 0:
                    ans2.Insert(0, a[a.Count - 3 - cnt]);
                    cnt += 2;
                    break;
            }
        }

        long sum = 0;
        for (int i = 1; i < ans.Count; i++)
        {
            sum += Math.Abs(ans[i] - ans[i - 1]);
        }

        long sum2 = 0;
        for (int i = 1; i < ans2.Count; i++)
        {
            sum2 += Math.Abs(ans2[i] - ans2[i - 1]);
        }
        Console.WriteLine(Math.Max(sum, sum2));
    }
}

Measured memory_bytes: 20188