akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
	int H, W;
	cin >> H >> W;
	vector<string> a(H);
	for(int i=0; i<H; ++i) cin >> a[i];
	vector<string> r, b;
	r=b=a;
	for(int i=0; i<H; ++i){
	    for(int j=0; j<W; ++j){
	        if(i==0) r[i][j]='#';
	        else if(i+1==H) b[i][j]='#';
	        else if(j%2==0) r[i][j]='#';
	        else b[i][j]='#';
	    }
	}
	for(int i=0; i<H; ++i) cout << r[i] << endl;
	cout << endl;
	for(int i=0; i<H; ++i) cout << b[i] << endl;
	return 0;
}


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

#define rep(i, a, b) for(int i = (a); i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())
#define endl '\n'

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

const ll mod = 1000000007;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// head

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

    int s;
    cin >> s;

    vector<int> dp(s + 1);
    dp[0] = 1;
    for(int i = 0; i <= s - 1; i++) {
        for(int j = 3; j <= s; j++) {
            if(i + j <= s) {
                dp[i + j] += dp[i];
                dp[i + j] %= mod;
            }
        }
    }
    cout << dp[s] << endl;
    return 0;
}


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

int main() {
	bool prime[1000000]={false};
	prime[1]=true;
	prime[2]=false;
	int n;
	while(cin>>n){
		int cnt=0;
		
		for(int j = 2; j * j <= n ; j++)
            if(!prime[j])
                for (int k = 2; k*j <= n;k++)
                   prime[j*k] = true;
	
		for(int i=2;i<=n;i++)
			if(!prime[i]) cnt++;
		cout<<cnt<<endl;
	}
	return 0;
}

Measured memory_bytes: 2140
import collections
import math

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

n,p= map(int, input().split())
s=list(input())
mod=0
ans=[]
count=0

if p==2 or p==5:
    for i in range(n):
        if p==2 and s[n-1-i] in ('0', '2' ,'4','6' ,'8'):
            count+=n-i
        elif p==5 and s[n-1-i] in ('0','5') :
            count+=n-i
    print(count)
    exit()

s+='0'

for i in range(n+1):
    if s[n-i]!=0:
        mod+=(pow(10,i,p)*int(s[n-i]))%p
        mod%=p
    ans.append(mod)

ans = collections.Counter(ans)
ans=ans.most_common()
for i in range(len(ans)):
    if ans[i][1]>=2:
        count+=combinations_count(ans[i][1],2)

print(count)

Measured memory_bytes: 69676
def main():
    import sys
    input = sys.stdin.readline
    N, M = map(int, input().split())
    AB = sorted([tuple(map(int, input().split())) for _ in range(N)])
    money = 0
    count = 0
    for a, b in AB:
        if count + b >= M:
            money += a * (M - count)
            break
        else:
            money += a * b
            count += b
    print(money)


if __name__ == '__main__':
    main()

Measured memory_bytes: 17732
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;

#define INF 1LL << 60
#define pb push_back
#define REP(i, n) for (int i = 0; i < (n); i++)
#define REPR(i, b, e) for (int i = (b); i <= (e); i++)
#define DEBUG(x) cout << #x << ": " << (x) << endl
#define DEBUGA(a) cout << #a << ": "; for (const auto& v: (a)) cout << v << endl

int main() {
    int N, K;
    string S;
    cin >> N >> K >> S;

    vi a;
    char cur = '1';
    int pos = 0;

    a.pb(0);
    REP(i, N) {
        if (S[i] == cur) {
            a[pos]++;
        } else {
            cur = S[i];
            a.pb(1);
            pos++;
        }
    }
    if (cur == '0') a.pb(0);

    int L = a.size();
    int csum[L + 1];
    csum[0] = 0;
    REP(i, L) csum[i+1] = csum[i] + a[i];

    int W = 2 * K + 1;
    int M = 0;
    for (int i = 0; i < L; i += 2) {
        int right = min(i + W, L);
        int s = csum[right] - csum[i];
        if (M < s) M = s;
    }

    cout << M << endl;
    return 0;
}


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

using namespace std;
typedef long long ll;
using Pll = pair<ll,ll>;

const ll INF = 1LL<<60;
const ll MOD = 1000000007;

//cout << fixed << setprecision(10);

int main() {
    string S;
    cin >> S;
    ll N = S.size();
    ll ans=1;
    ll idx=1;
    string tmp="";
    char ch=S[0];
    while(idx<N){
        if(ch==S[idx]){
            idx++;
            if(idx<N){
                ans++;
                ch = 'z'+1;
                idx++;
            }
        }
        else{
            ans++;
            ch = S[idx];
            idx++;
        }
    }

    ll ans2=1;
    idx=2;
    ch = 'z'+1;
    while(idx<N){
        if(ch==S[idx]){
            idx++;
            if(idx<N){
                ans2++;
                ch = 'z'+1;
                idx++;
            }
        }
        else{
            ans2++;
            ch = S[idx];
            idx++;
        }
    }
    
    cout << max(ans,ans2) << endl;

    return 0;
}

Measured memory_bytes: 640
n = int(input())
a_str = input()
b_str = input()
c_str = input()

ans = 0
for a, b, c in zip(a_str, b_str, c_str):
    if a == b == c:
        continue
    elif a == b or b == c or c == a:
        ans += 1
    else:
        ans += 2
print(ans)

Measured memory_bytes: 9176
#include<bits/stdc++.h>
using namespace std;
#define N 2000010
int v[N],n,va[N],mx,c[N];
char s[N];
struct st{
	int mx[N];
	void bd(int o,int l,int r){
		mx[o]=-1e9;
		if(l==r)return;
		int md=(l+r)/2;
		bd(o*2,l,md);
		bd(o*2+1,md+1,r);
	}
	void mod(int o,int l,int r,int x,int y){
		if(l==r){
			mx[o]=y;
			return;
		}
		int md=(l+r)/2;
		if(x<=md)mod(o*2,l,md,x,y);
		else mod(o*2+1,md+1,r,x,y);
		mx[o]=max(mx[o*2],mx[o*2+1]);
	}
	int q(int o,int l,int r,int x,int y){
		if(r<x||y<l)return -1e9;
		if(x<=l&&r<=y)return mx[o];
		int md=(l+r)/2;
		return max(q(o*2,l,md,x,y),q(o*2+1,md+1,r,x,y));
	}
}a,b;
int ck(int x,int v){
	if(v<0)return 0;
	if(v&1)return a.q(1,1,n,x,n)>=v;
	return b.q(1,1,n,x,n)>=v;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		scanf("%d",&v[i]);
		if(v[i]>mx){
			mx=v[i];
			va[i]=2;
		}
		else va[i]=1;
	}
	a.bd(1,1,n);
	for(int i=n;i;i--){
		int m1=a.q(1,1,n,v[i],n),m0=b.q(1,1,n,v[i],n);
		if(va[i]==1){
			a.mod(1,1,n,v[i],m0+1);
			b.mod(1,1,n,v[i],m1+1);
		}
		else{
			a.mod(1,1,n,v[i],m1+2);
			b.mod(1,1,n,v[i],m0+2);
		}
		c[i]=c[i+1]+va[i]-1;
	}
	int cx=0,cy=0,mx=0,my=0;
	for(int i=1;i<=n;i++){
		a.mod(1,1,n,v[i],-1e9);
		b.mod(1,1,n,v[i],0);
		if(ck(my,cx+c[i+1]-cy+(v[i]>mx))){
			s[i]='0';
			cx+=(v[i]>mx);
			mx=max(mx,v[i]);
		}
		else if(ck(max(mx,v[i]),cy+c[i+1]-cx-(v[i]>mx))){
			s[i]='0';
			cx+=(v[i]>mx);
			mx=max(mx,v[i]);
		}
		else{
			s[i]='1';
			cy+=(v[i]>my);
			my=max(my,v[i]);
		}
	}
	if(cx!=cy)puts("-1");
	else cout<<s+1;
}

Measured memory_bytes: 16896
#include<iostream>
using namespace std;
int arr[200000];
int main()
{
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n-1;i++)cin>>a[i];
    for(int i=0;i<n-1;i++)arr[a[i]]++;
    for(int i=1;i<=n;i++)cout<<arr[i]<<endl;
    return 0;
}


Measured memory_bytes: 4704
int main (void) {
	char str[20];
	int l = sizeof(str) / sizeof(char);
	int r = 999;
	gets(str);
	for (int i = 0; i < 9; i++) {
		char s[5] = {};
		sprintf(s, "%c%c%c", str[i], str[i + 1], str[i + 2]);
		if (abs(753 - atoi(s)) < r) {
			r = abs(753 - atoi(s));
		}
	}
	printf("%d\n", r);
	return 0;
}

Measured memory_bytes: 128
#include<stdio.h>
#define MAX 251

typedef struct{
  int key;
  int parent;
  int left;
  int right;
}Dot;

Dot A[MAX];

void Print(int i){
  printf("node %d: ",i);
  printf("key = %d, ",A[i].key);
  if(A[i].parent)printf("parent key = %d, ",A[A[i].parent].key);
  if(A[i].left) printf("left key = %d, ",A[A[i].left].key);
  if(A[i].right)printf("right key = %d, ",A[A[i].right].key);
  printf("\n");
}


int main(){
  int n;
  int i;

  scanf("%d",&n);
  for(i=1;i<=n;i++){//i=nodeで１オリジンにしたから、みんなずれる。0番目作らない
    scanf("%d",&A[i].key);//配列は層ごとに左から、値は入力されたものを使う
    A[i].parent=i/2;//親、子供を
    if(2*i<=n)A[i].left=2*i;
    if(2*i+1<=n) A[i].right=2*i+1;
  }
  
  for(i=0;i<n;i++) Print(i+1);
  return 0;
}





Measured memory_bytes: 2036
N,K=map(int,input().split())
S=input()
bef=S[0]
idx=[0]
for i in range(1,N):
    if S[i]!=bef:
        idx.append(i)
        bef=S[i]
ans=0
for i,x in enumerate(idx):
    if x==0 and S[0]=="0":
        end=i+2*K
        if end>=len(idx):
            end=N
        else:
            end=idx[end]
        ans=max(ans,end-x)
    if S[x]=="1":
        end=i+2*K+1
        if end>=len(idx):
            end=N
        else:
            end=idx[end]
        ans=max(ans,end-x)
print(ans)

Measured memory_bytes: 7160
#include<stdio.h>
int main(){
  int n,m[10000],i,sum;
  while(1){
    sum=0;
    scanf("%d",&n);
    if(n==0)break;
    for(i=0;i<n/4;i++){
      scanf("%d",&m[i]);
      sum+=m[i];
    }
    printf("%d\n",sum);
  }
  return 0;
}
  

Measured memory_bytes: 604
#pragma GCC target("avx")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("-fgcse")
#pragma GCC optimize("-fgcse-lm")
#pragma GCC optimize("-fipa-sra")
#pragma GCC optimize("-ftree-pre")
#pragma GCC optimize("-ftree-vrp")
#pragma GCC optimize("-fpeephole2")
#pragma GCC optimize("-ffast-math")
#pragma GCC optimize("-fsched-spec")
#pragma GCC optimize("unroll-loops")
#pragma GCC optimize("-falign-jumps")
#pragma GCC optimize("-falign-loops")
#pragma GCC optimize("-falign-labels")
#pragma GCC optimize("-fdevirtualize")
#pragma GCC optimize("-fcaller-saves")
#pragma GCC optimize("-fcrossjumping")
#pragma GCC optimize("-fthread-jumps")
#pragma GCC optimize("-funroll-loops")
#pragma GCC optimize("-fwhole-program")
#pragma GCC optimize("-freorder-blocks")
#pragma GCC optimize("-fschedule-insns")
#pragma GCC optimize("inline-functions")
#pragma GCC optimize("-ftree-tail-merge")
#pragma GCC optimize("-fschedule-insns2")
#pragma GCC optimize("-fstrict-aliasing")
#pragma GCC optimize("-fstrict-overflow")
#pragma GCC optimize("-falign-functions")
#pragma GCC optimize("-fcse-skip-blocks")
#pragma GCC optimize("-fcse-follow-jumps")
#pragma GCC optimize("-fsched-interblock")
#pragma GCC optimize("-fpartial-inlining")
#pragma GCC optimize("no-stack-protector")
#pragma GCC optimize("-freorder-functions")
#pragma GCC optimize("-findirect-inlining")
#pragma GCC optimize("-fhoist-adjacent-loads")
#pragma GCC optimize("-frerun-cse-after-loop")
#pragma GCC optimize("inline-small-functions")
#pragma GCC optimize("-finline-small-functions")
#pragma GCC optimize("-ftree-switch-conversion")
#pragma GCC optimize("-foptimize-sibling-calls")
#pragma GCC optimize("-fexpensive-optimizations")
#pragma GCC optimize("-funsafe-loop-optimizations")
#pragma GCC optimize("inline-functions-called-once")
#pragma GCC optimize("-fdelete-null-pointer-checks")
// by piano
#include<bits/stdc++.h>
#define inf (0x7f7f7f7f)
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define Min(a, b) ((a) < (b) ? (a) : (b))
typedef long long ll;
using namespace std;
template <class T>
inline void read(T &x){
	int f = 0, ch = 0; x = 0;
	for(; !isdigit(ch); ch = getchar()) if(ch == '-') f = 1;
	for(; isdigit(ch); ch = getchar()) x = x * 10 + ch - '0';
	if(f) x = -x;
}
int a[100005], n;
int main(){
	read(n); int ans = 0;
	for(int i = 1; i <= n; i++) read(a[i]);
	for(int i = 2; i <= n; i++)
		if(a[i] == a[i-1]) a[i] = -1, ans++; 
	cout << ans << endl;
	return 0;
}
 

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <map>

using namespace std;

int main(int argc, char const *argv[])
{
    int N;
    cin >> N;
    map<int, int> D;
    int in;
    for (int i = 0; i < N; i++)
    {
        cin >> in;
        D[in]++;
    }

    int M;
    cin >> M;
    for (int i = 0; i < M; i++)
    {
        cin >> in;
        D[in]--;
        if (D[in] < 0)
        {
            cout << "NO" << endl;
            return 0;
        }

    }

    cout << "YES" << endl;

    return 0;
}

Measured memory_bytes: 9600
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int in(void){
	int i;scanf("%d",&i);
	return i;
}
long long llin(void){
	long long i;scanf("%lld",&i);
	return i;
}
void chin(char s[]){
	scanf("%s",s);
}
void print(int a){
	printf("%d\n",a);
}
void llprint(long long a){
	printf("%lld\n",a);
}
void print2(int a,int b){
	printf("%d %d\n",a,b);
}
long long max(long long a,long long b){
	return a>b?a:b;
}
long long min(long long a,long long b){
	return a<b?a:b;
}
#define last(a) strlen(a)-1
int main(void){
	char a[11],b[11],c[11];
	chin(a);
	chin(b);
	chin(c);
	if(a[last(a)]==b[0]&&b[last(b)]==c[0]){
		puts("YES");
	}
	else{
		puts("NO");
	}
	return 0;
}

Measured memory_bytes: 128
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <numeric>
    
using namespace std;    
typedef long long ll;
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()

int main(){

    int n;
    cin >> n;

    vector<int> v(n + 1);
    for(int i = 1; i <= n; i++){
        cin >> v[i];
    }

    int next = 1;
    int ans = 0;
    for(int i = 0; i < n; i++){
        ans ++;
        next = v[next];
        if(next == 2){
            cout << ans << endl;
            return 0;
        }
    }

    cout << -1 << endl;

}

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

int main(int argc, char const *argv[])
{
  int H,W;
  cin >> H >> W;

  vector<string> imgRow;
  string input;
  for(int i=0; i<H; i++){
    cin >> input;
    imgRow.push_back(input);
  }
  for(int i=0; i<H; i++){
    cout << imgRow.at(i) << endl;
    cout << imgRow.at(i) << endl;
  }
  return 0;
}


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

int main() {
 int N,a,b;
  a=0;b=0;
  cin>>N;
  vector<int>A(N);
  for(int i=0;i<N;i++){
    cin>>A.at(i);
  }
  sort(A.begin(),A.end());
  reverse(A.begin(),A.end());
  for(int i=0;i<N;i++){
   if(i%2==0){
    a=a+A.at(i);
   }
   else{
    b=b+A.at(i);
   }
  }
 cout<<a-b<<endl;
}


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

#define int long long
typedef pair<int, int> P;
#define mod 1000000007
#define INF (1LL<<60)
 
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define repi(itr, ds) for (auto itr = ds.begin(); itr != ds.end(); itr++)
#define YES puts("YES")
#define Yes puts("Yes")
#define NO  puts("NO")
#define No  puts("No")
int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
 
const int dx[4] = { 1, 0, -1, 0 };
const int dy[4] = { 0, 1, 0, -1 };
 
 
#if 1
//-------------
// DUMPマクロ
// https://www.creativ.xyz/dump-cpp-652/
 
// vector
template <typename T>
istream& operator>>(istream& is, vector<T>& vec) {
    for (T& x : vec) is >> x;
    return is;
}
// pair
template <typename T, typename U>
ostream& operator<<(ostream& os, pair<T, U>& pair_var) {
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}
// vector
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
// map
template <typename T, typename U>
ostream& operator<<(ostream& os, map<T, U>& map_var) {
    os << "{";
    repi(itr, map_var) {
        os << *itr;
        itr++;
        if (itr != map_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
// set
template <typename T>
ostream& operator<<(ostream& os, set<T>& set_var) {
    os << "{";
    repi(itr, set_var) {
        os << *itr;
        itr++;
        if (itr != set_var.end()) os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
 
#define DUMPOUT cerr
 
void dump_func() {
    DUMPOUT << endl;
}
template <class Head, class... Tail>
void dump_func(Head&& head, Tail&& ... tail) {
    DUMPOUT << head;
    if (sizeof...(Tail) > 0) {
        DUMPOUT << ", ";
    }
    dump_func(std::move(tail)...);
}
#ifdef DEBUG
#define DEB
#define dump(...)                                                              \
    DUMPOUT << "  " << string(#__VA_ARGS__) << ": "                            \
            << "[" << to_string(__LINE__) << ":" << __FUNCTION__ << "]"        \
            << endl                                                            \
            << "    ",                                                         \
        dump_func(__VA_ARGS__)
#else
#define DEB if (false)
#define dump(...)
#endif
#endif


signed main() {
    int N, K;
    cin>>N>>K;
    int ans=0;
    rep(i,N){
        int a; cin>>a;
        if(a<=K/2) ans+=a*2;
        else ans+=(K-a)*2;
    }
    cout<<ans<<endl;
    
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using Int = long long;
array<Int, 18> POW10;
int main()
{
    POW10[0] = 1;
    for (int i = 1; i < POW10.size(); i++) POW10[i] = POW10[i-1] * 10;
    int D; cin >> D;
    int digits = 0;
    for (int val = 1; val <= D; val *= 10, digits++) {}
    Int ans = 0;
    for (int d = digits; d <= digits*2; d++) {
        vector<Int> A, S = {0};
        for (int k = d/2; k < d; k++) {
            A.push_back(POW10[k] - POW10[d-1-k]);
            S.push_back(S.back() + A.back());
        }
        function<void(int, Int, Int)> recur = [&](int idx, Int rest, Int acc) {
            int ten = (idx == A.size()-1 ? 9 : 10);
            if (idx == 0) {
                if (A[0] == 0) { if (rest == 0) ans += acc * ten; }
                else if (rest % A[0] == 0 && abs(rest / A[0]) <= 9) ans += acc * (ten - abs(rest / A[0]));
            } else {
                for (int i = -9; i <= 9; i++) {
                    Int r = rest - i * A[idx];
                    if (abs(r) <= abs(S[idx]*9)) recur(idx-1, r, acc * (ten - abs(i)));
                }
            }
        };
        recur(A.size()-1, D, 1);
    }
    cout << ans << '\n';
    return 0;
}

Measured memory_bytes: 256
n = gets.to_i

ret_arr = []
n.times do
	command = gets.split
	case command[0]
	when "insert"
		num = command[1].to_i
		ret_arr.unshift(num)
	when "delete"
		num = command[1].to_i
		index = ret_arr.find_index {|val| val == num}
		if index != nil
			ret_arr.delete_at(index)
		end
	when "deleteFirst"
		ret_arr.shift
	when "deleteLast"
		ret_arr.pop
	end
end

puts ret_arr.join(" ")

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

int main()
{
int a,b,c;
  cin>>a>>b>>c;
  
  bool ans=false;
    
  if(a==b&&a!=c)
    ans=true;
  
  else if(b==c&&b!=a)
    ans=true;
  
  else if(a==c&&b!=a)
    ans=true;
  
  else ans=false;  
  
  if(ans)
    cout<<"Yes"<<endl;
  else
    cout<<"No"<<endl;
}

Measured memory_bytes: 256
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-7-16 14:04:12
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

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

// const int C = 1e6+10;
// const ll M = 1000000007;

int N;
int M;
string S;
vector<string> V;
vector<string> W;

void make_V()
{
  int a = 0;
  int b = 0;
  int start = 0;
  for (auto i = 0; i < M; i++)
  {
    if (S[i] == 'a')
    {
      a++;
    }
    else
    {
      b++;
    }
    if (a == b)
    {
      a = b = 0;
      V.push_back(S.substr(start, i + 1 - start));
      start = i + 1;
    }
  }
}

vector<int> make_num(string str)
{
  vector<int> num;
  int a = 0;
  int b = 0;
  for (auto c : str)
  {
    if (c == 'a')
    {
      num.push_back(a);
      a++;
    }
    else
    {
      num.push_back(b);
      b++;
    }
  }
  return num;
}

string calc_a(string str)
{
  vector<int> num = make_num(str);
  string res = "";
  bool is_a = true;
  int search = -1;
  for (auto i = 0; i < (int)str.size(); i++)
  {
    if (is_a && str[i] == 'a')
    {
      res += "a";
      search = num[i];
      is_a = false;
    }
    else if ((!is_a) && str[i] == 'b')
    {
      if (num[i] == search)
      {
        res += "b";
        is_a = true;
      }
    }
  }
  return res;
}

string calc_b(string str)
{
  vector<int> num = make_num(str);
  vector<string> X;
  for (auto k = 0; k <= (int)str.size() / 2; k++)
  {
    string temp = "";
    for (auto i = 0; i < (int)str.size(); i++)
    {
      if (num[i] >= k)
      {
        string s{str[i]};
        temp += s;
      }
    }
    X.push_back(temp);
  }
  return *max_element(X.begin(), X.end());
}

int main()
{
  cin >> N >> S;
  M = 2 * N;
  make_V();
  for (auto str : V)
  {
    if (str[0] == 'a')
    {
      W.push_back(calc_a(str));
    }
    else
    {
      W.push_back(calc_b(str));
    }
  }
  reverse(W.begin(), W.end());
  string ans = "";
  for (auto str : W)
  {
    if (ans < str + ans)
    {
      ans = str + ans;
    }
  }
  cout << ans << endl;
}

Measured memory_bytes: 16256
package main

import "fmt"

func main() {
	var a int
	fmt.Scanf("%d", &a)

	if a < 10 {
		fmt.Println(a)
	} else {
		var cnt, rem, sum int
		for {
			rem = a % 10
			sum += rem
			cnt++
			a = a / 10
			if a == 0 {
				break
			}
		}

		if sum > rem+(cnt-1)*9-1 {
			fmt.Println(sum)
		} else {
			fmt.Println(rem + (cnt-1)*9 - 1)
		}
	}

}


Measured memory_bytes: 512
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#

"""
agc022 B
"""

n = int(input())


def nagase(n):
    m, r = divmod(n, 8)
    reg = []
    for i in range(m):
        reg.append(i*12+2)
        reg.append(i*12+3)
        reg.append(i*12+4)
        reg.append(i*12+6)
        reg.append(i*12+8)
        reg.append(i*12+9)
        reg.append(i*12+10)
        reg.append(i*12+12)
    if r == 1:
        reg.append(m*12+6)
    elif r == 2:
        reg.append((m)*12+2)
        reg.append((m)*12+4)
    elif r == 3:
        if m == 0:
            reg = [2, 5, 63]
        else:
            reg.append((m)*12+2)
            reg.append((m)*12+4)
            reg.append((m)*12+6)
    elif r == 4:
        if m == 0:
            reg = [2, 5, 20, 63]
        else:
            reg.append((m)*12+2)
            reg.append((m)*12+4)
            reg.append((m)*12+6)
            reg.append((m)*12+12)
    elif r == 5:
        reg.append((m)*12+2)
        reg.append((m)*12+3)
        reg.append((m)*12+4)
        reg.append((m)*12+6)
        reg.append((m)*12+9)
    elif r == 6:
        reg.append((m)*12+2)
        reg.append((m)*12+3)
        reg.append((m)*12+4)
        reg.append((m)*12+6)
        reg.append((m)*12+9)
        reg.append((m)*12+12)
    elif r == 7:
        reg.append((m)*12+2)
        reg.append((m)*12+3)
        reg.append((m)*12+4)
        reg.append((m)*12+6)
        reg.append((m)*12+8)
        reg.append((m)*12+9)
        reg.append((m)*12+10)
    return reg


print(" ".join(map(str, nagase(n))))





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

int main(){
    int N,K,sum=0;
    cin >> N >> K;
    int L[N];
    for(int i=0;i<N;i++) cin >> L[i];

    sort(L,L+N,greater<int>());

    for(int i=0;i<K;i++) sum+=L[i];

    cout << sum << endl; 

}

Measured memory_bytes: 256
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

typedef long long ll;

int main(){
  ll n;
  ll i;
  ll cnt = 0;

  scanf("%lld", &n);

  if(n % 2 == 1){
    printf("0\n");
    return 0;
  }

  i = 5;
  while(n > i){
    cnt += n/(i*2);
    i = i*5;
  }

  printf("%lld\n", cnt);

  return 0;
}


Measured memory_bytes: 128
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
#include <map>
#define all(a) (a).begin(),a.end()
#define pb push_back
using namespace std;

class UnionFind {
private:
  vector<int> data;  
public:
  UnionFind(int size) : data(size, -1) { }
  bool unionSet(int x, int y) {
    x = root(x); y = root(y);
    if (x != y) {
      if (data[y] < data[x]) swap(x, y);
      data[x] += data[y]; data[y] = x;
    }
    return x != y;
  }
  bool findSet(int x, int y) {
    return root(x) == root(y);
  }
  int root(int x) {
    return data[x] < 0 ? x : data[x] = root(data[x]);
  }
  int size(int x) {
    return -data[root(x)];
  }
};

int main(void){

  int N,K,L;
  int a,b;
  int i,j;

  cin>>N>>K>>L;
  UnionFind uf1(N+1),uf2(N+1);

  for(i=0;i<K;i++){
    cin>>a>>b;
    uf1.unionSet(a,b);
  }
  for(i=0;i<L;i++){
    cin>>a>>b;
    uf2.unionSet(a,b);
  }

  vector<pair<int,int> >p;
  map<pair<int,int>,int> pp;
  
  for(i=1;i<=N;i++){
    if(pp.find(pair<int,int>(uf1.root(i),uf2.root(i)))==pp.end()) pp[pair<int,int>(uf1.root(i),uf2.root(i))]=1;
    else pp[pair<int,int>(uf1.root(i),uf2.root(i))]++; 
  }
  for(i=1;i<=N;i++){
    cout<<pp[pair<int,int>(uf1.root(i),uf2.root(i))]<<" ";
  }
  cout<<endl;
  return 0;
}

Measured memory_bytes: 13568
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(), (x).end()
#define ll long long
#define INF 1000000000000000000

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

    int N, M;
    cin >> N >> M;
    ll dx[8] = {1, 1, 1, 1, -1, -1, -1, -1};
    ll dy[8] = {1, -1, -1, 1, 1, 1, -1, -1};
    ll dz[8] = {1, 1, -1, -1, 1, -1, 1, -1};

    vector<ll> x(N), y(N), z(N);

    rep(i, N) { cin >> x[i] >> y[i] >> z[i]; }

    ll ans = 0;
    rep(i, 8) {
        vector<ll> sums;
        rep(j, N) {
            ll temp = x[j] * dx[i] + y[j] * dy[i] + z[j] * dz[i];
            sums.push_back(temp);
        }

        sort(all(sums), greater<ll>());
        ll can = accumulate(sums.begin(), sums.begin() + M, (ll)0);
        ans = max(ans, can);
    }

    cout << ans << endl;
}

Measured memory_bytes: 256
import java.util.Arrays;
import java.util.Scanner;
public class Main{
	public static void main(String[] args)throws Exception{
		new Main().solve();
	}
	void solve(){
		Scanner sc=new Scanner(System.in);
		while(true){
			int n=sc.nextInt();//the number of cities
			int m=sc.nextInt();//the number of paths
			if(n==0&&m==0)break;
			int INF=Integer.MAX_VALUE/4;
			int[][] ldis=new int[n][n];
			int[][] sdis=new int[n][n];
			for(int i=0;i<n;i++){
				for(int j=0;j<n;j++){
					if(i==j)continue;
					ldis[i][j]=INF;
					sdis[i][j]=INF;
				}
			}
			for(int i=0;i<m;i++){
				int x=sc.nextInt()-1;
				int y=sc.nextInt()-1;
				int t=sc.nextInt();
				String str=sc.next();
				if(str.equals("L")){
					ldis[x][y]=t;
					ldis[y][x]=t;
				}else if(str.equals("S")){
					sdis[x][y]=t;
					sdis[y][x]=t;
				}
			}

			for(int k=0;k<n;k++){
				for(int i=0;i<n;i++){
					for(int j=0;j<n;j++){
						if(i==j)continue;
						ldis[i][j]=Math.min(ldis[i][j],ldis[i][k]+ldis[k][j]);
						sdis[i][j]=Math.min(sdis[i][j],sdis[i][k]+sdis[k][j]);
					}
				}
			}
			int r=sc.nextInt();
			int[] destination=new int[r];
			for(int i=0;i<r;i++){
				destination[i]=sc.nextInt()-1;
			}
			int[][] dp=new int[r][n];
			for(int i=0;i<r;i++){
				for(int j=0;j<n;j++){
					dp[i][j]=INF;
				}
			}
			dp[0][destination[0]]=0;//dp[i][j]???i???????????§?¨?????????????j????????????????????´???????????????
			for(int i=1;i<r;i++){
				for(int j=0;j<n;j++){
					for(int k=0;k<n;k++){
						if(k==j){
							dp[i][j]=
									Math.min(dp[i][j],
											ldis[destination[i]][destination[i-1]]
													+dp[i-1][j]);
							continue;
						}
						dp[i][j]=Math.min(dp[i][j],ldis[destination[i]][j]+sdis[j][k]+ldis[k][destination[i-1]]+dp[i-1][k]);
					}
				}
			}
			int min=9999999;
			for(int i=0;i<n;i++){
				min=Math.min(dp[r-1][i],min);
			}
			System.out.println(min);
		}
	}
	void tr(Object...o){System.out.println(Arrays.deepToString(o));}
}

Measured memory_bytes: 82952
#include <cctype>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <cmath>
#define pk putchar(' ')
#define ph puts("")
typedef long long ll;
using namespace std;
template <class T>
void rd(T &x)
{
    x = 0;
    int f = 1;
    char c = getchar();
    while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
    while (isdigit(c)) x = (x << 3) + (x << 1) + (c ^ 48), c = getchar();
    x *= f;
}
template <class T>
void pt(T x)
{
    if (x < 0)
        putchar('-'), x = (~x) + 1;
    if (x > 9)
        pt(x / 10);
    putchar(x % 10 ^ 48);
}
int n;
int main() 
{
	rd(n);
	for (int i = 0; ; i++)
		for (int j = -1280; j <= 1280; j++)
			if (i * i * i * i * i - j * j * j * j * j == n)
				return !printf("%d %d\n", i, j);
    return 0;
}

Measured memory_bytes: 1604
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define fi first
#define se second
#define pb push_back
#define rep(i, s, n) for (int i = s; i < n; i++)
#define rrep(i, s, n) for (int i = (n)-1; i >= (s); i--)
#define all(a) a.begin(),a.end()
typedef pair<int,int>pint;
typedef vector<int>vint;
typedef vector<pint>vpint;
const long long MOD = 1000000007, INF = 1e17;
 
#define endl '\n'
#define IOS() ios_base::sync_with_stdio(0);cin.tie(0)
 
template<class T>inline bool chmax(T& a,T b){if(a<b){a=b;return true;}return false;}
template<class T>inline bool chmin(T& a,T b){if(a>b){a=b;return true;}return false;}


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

signed main()
{
	IOS();
	int H,W;
	vector<int>ans;
	while(1){
		cin>>W>>H;
		if(H==0&&W==0)break;
		string s[H];
		rep(i,0,H)cin>>s[i];
		queue<pair<int,int>>que;
		rep(i,0,H){
			rep(j,0,W){
				if(s[i][j]=='@')que.push({i,j});
			}
		}
		vector<vector<int>>visit(H,vector<int>(W,0));
		while(!que.empty()){
			int i = que.front().fi;
			int j = que.front().se;
			que.pop();
			if(visit[i][j])continue;
			visit[i][j] = true;
			rep(k,0,4){
				int ni = i + dx[k];
				int nj = j + dy[k];
				if(ni<0||nj<0||H<=ni||W<=nj)continue;
				if(s[ni][nj]=='#')continue;
				if(visit[ni][nj])continue;
				que.push({ni,nj});
			}
		}
		int res = 0;
		rep(i,0,H)rep(j,0,W)if(visit[i][j])res++;
		ans.push_back(res);
	}
	for(auto e:ans){
		cout<<e<<endl;
	}
}



Measured memory_bytes: 3192
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
typedef long long ll;
#define debug(x) cerr << __LINE__ << " : " << #x << " = " << (x) << endl;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define FORR(i,a,b) for(int i=(int)(b)-1;i>=(int)(a);i--)
#define CHMIN(a,b) (a) = min((a),(b))
#define CHMAX(a,b) (a) = max((a),(b))

// left:0 right:1

int main()
{
    char str[35]={};
    int ans;
    int len;
    int act;
    int lr[26]={0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,1,0,0,0,1,0};
    while(1==1)
    {
        ans=0;
        REP(i,35)str[i]='\0';
        scanf("%s",str);
        if(str[0]=='#')break;
        len=strlen(str);
        act=lr[str[0]-'a'];
        REP(i,len)
        {
            if(lr[str[i]-'a']!=act)
            {
                ans++;
                act=1-act;
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}


Measured memory_bytes: 3228
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <bitset>
#include <algorithm>
#include <complex>
using namespace std;
 
#define REP(i,n) for(int i=0; i<n; ++i)
#define FOR(i,a,b) for(int i=a; i<=b; ++i)
#define FORR(i,a,b) for (int i=a; i>=b; --i)
#define ALL(c) (c).begin(), (c).end()
 
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<VL> VVL;
typedef vector<VI> VVI;
typedef pair<int,int> P;
typedef pair<ll,ll> PL;
typedef vector<double> VD;

int in() { int x; scanf("%d", &x); return x; }
ll lin() { ll x; scanf("%lld", &x); return x; }

int main() {
    int a, b;
    cin >> a >> b;
    int d = b - a;
    cout << (d * (d + 1) / 2 - b) << endl;

    return 0;
}


Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;

namespace abc82_c
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            int[] input = ReadLine().Split().Select(int.Parse).ToArray();

            var dic = new Dictionary<int,int>();

            //count the number of occurrences
            for(int i=0; i<n; i++){
                if(dic.ContainsKey(input[i])) dic[input[i]]++;
                else dic[input[i]] = 1;
            }

            int cnt=0;
            foreach(KeyValuePair<int,int> item in dic){
                if(item.Key<=item.Value) cnt += item.Value-item.Key;
                else cnt += item.Value;
            }
            WriteLine($"{cnt}");
        }
    }
}

Measured memory_bytes: 26460
#include<bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define int long long
#define vec(a,n) vector<int> (a)((n));
#define Vec(a,n) vector<string> (a)((n));
#define twovec(a,n,m) vector<vector<int>> a(n,vector<int>(m,0));
#define Twovec(a,n,m) vector<vector<double>> a(n,vector<double>(m,0));
#define P pair<int,int>
#define All(a) (a).begin(),(a).end()
#define Sort(a) sort(All(a));
#define Reverse(a) reverse(All(a));
#define PQ(n) priority_queue<P,vector<P>,greater<P>> (n)
#define pq(n) priority_queue<int> (n)
#define print(a) cout << (a) << endl;
#define printD(a) cout << setprecision(15) << (a) << endl;
using namespace std;
int max_int = 1000000007;
double pi = 3.1415926535;
void Debug(auto a);
int nibul(auto a,auto b);
int nibuu(auto a,auto b);
void input(vector<int>& a,int n);

int n;

signed main(){
    cin >> n;
    string s;
    cin >> s;
    REP(i,s.size()){
        int x = s[i]-'A';
        x = (x+n)%26;
        s[i] = x + 'A';
    }
    print(s);
    return 0;
}

void Debug(auto a){
    cout << "{ ";
    for(auto b: a){
        cout << b << " ";
    }
    cout << "}" << endl;
}
int nibul(auto a,auto b){
    int x = lower_bound(All(a),b) - a.begin();
    //key以上の初めてのitr
    return x;
}
int nibuu(auto a,auto b){
    int x = upper_bound(All(a),b) - a.begin();
    //key以下の最後のitr
    return x-1;
}

void input(vector<int>& a,int n){
    REP(i,n){
        cin >> a[i];
    }
}


Measured memory_bytes: 256
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <iomanip>
using namespace std;
//typedef __int64 LL;
typedef long long int LL;
typedef vector<int> ivec;
typedef vector<string> svec;
typedef pair<int,int> P;
//typedef pair<LL,LL> PL;

const int MOD=1000000007;


LL beki(LL a,LL b)
{
	if(b==0)return 1;
	LL x=beki(a,b/2);
	if(b%2==0)return (x*x)%MOD;
	else return (((a*x)%MOD)*x)%MOD;
}

LL inv(LL a)
{
	return beki(a,MOD-2);
}

LL kaijou(LL a)
{
	LL ans=1;
	for(LL i=1;i<=a;i++)
	{
		ans=(ans*i)%MOD;
	}			
	return ans;
}

LL combi(LL a,LL b)
{
	LL ret=1;
	for(LL i=1;i<=b;i++)
	{
		ret=(((ret*(a+1-i))%MOD)*inv(i))%MOD;
	}
	return ret;
}

int main(){
	LL x,y;cin>>x>>y;
	if((x+y)%3!=0 || 2*x<y || 2*y<x)
	{
		cout<<0<<"\n";
		return 0;
	}
	
	LL a=(2*y-x)/3,b=(2*x-y)/3;
	
	
	cout<<combi(a+b,b)<<"\n";
	return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<unordered_map>
#include<utility>
#include<cmath>
#include<random>
#include<cstring>
#include<queue>
#include<stack>
#include<bitset>
#include<cstdio>
#include<sstream>
#include<iomanip>
#include<assert.h>
#include<typeinfo>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
#define FOR(i,a) for(auto i:a)
#define pb push_back
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
#define show1d(v) rep(i,v.size())cout<<" "<<v[i];cout<<endl<<endl;
#define show2d(v) rep(i,v.size()){rep(j,v[i].size())cout<<" "<<v[i][j];cout<<endl;}cout<<endl;
using namespace std;
typedef long long ll;
typedef int Def;
typedef pair<Def,Def> pii;
typedef vector<Def> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<Def,pii> pip;
typedef vector<pip>vip;
template<typename A,typename B>bool cmin(A &a,const B &b){return a>b?(a=b,true):false;}
template<typename A,typename B>bool cmax(A &a,const B &b){return a<b?(a=b,true):false;}
const double PI=acos(-1);
const double EPS=1e-9;
Def inf = sizeof(Def) == sizeof(long long) ? 2e18 : 1e9+10;
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};
int main(int argc, char *argv[])
{
  string s;
  cin >> s;
  if (s.size() > 2) {
    reverse(s.begin(), s.end());
    cout << s << endl;
  } else {
    cout << s << endl;
  }
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
typedef long long ll;
namespace mp = boost::multiprecision;
using Mint = mp::cpp_int;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repi(i,a,b) for(int i = int(a); i < int(b); i++)
#define all(v) v.begin(), v.end()
#define uni(v) v.erase(unique(all(v)), v.end())
#define sort_g(v) sort(all(v), greater<int>())
#define dump(x) cerr << #x << ' ' << '=' << ' ' << x << endl

int main() {
    int s;
    cin >> s;
    vector<int> data(1000001);
    data.at(s) = 1;

    int i = 2;
    int ans;
    while(true) {
        if(s % 2 == 0) {
            s = s / 2;
        } else {
            s = 3 * s + 1;
        }
        if(data.at(s) != 0) {
            ans = i;
            break;
        } else {
            data.at(s)++;
        }
        i++;
    }

    cout << ans << endl;
}


Measured memory_bytes: 4096
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const ll mod = 1000000007;
const ll INF = 1001001001;
const ll LINF = 1001001001001001001;

void prvec(vector<ll> vec){
    ll n = vec.size();
    rep(i,n) cout << "i" << " " << vec.at(i) << "\n";
}

void pr2d(vector<vector<ll>> vvec){
    ll h = vvec.size();
    ll w = vvec.at(0).size();
    rep(i,h){
        rep(j,w){
            cout << vvec.at(i).at(j) << " ";
        }
        cout << "\n";
    }
}

int main(){
    ll n ; cin >> n;
    deque<ll> a;
    rep(i,n){
        ll x; cin >> x;
        auto it = lower_bound(a.begin(),a.end(),x);
        if(it==a.begin()){
            a.push_front(x);
        }else{
            ll y = it-a.begin();
            a.at(y-1) = x;
        }
    }
    cout << a.size() << endl;
}

Measured memory_bytes: 1024
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdint>
#include<cstdlib>
template<typename T>
void fin(T const& t){ std::cout << t << std::endl; exit(0); }

template<typename T>
std::vector<std::vector<T>> mk2d(size_t s1, size_t s2, T const& val) {
  std::vector<T> tmp(s2, val);
  return std::vector<std::vector<T>>(s1, tmp);
}

int const MAXL = 1e5;

int msb_(int x) { return 31 - __builtin_clz(x); }

int main() {
  std::cin.tie(0); std::ios::sync_with_stdio(false);
  int N; std::cin >> N;
  std::vector<int> V(N), W(N);
  for(int i = 0; i < N; ++i) std::cin >> V[i] >> W[i];
  int pN = std::min(N+1, 512);
  auto dp = mk2d(pN, MAXL+1, (int)0);
  for(int i = 1; i < pN; ++i) {
    int pi = i/2;
    // don't use V[i-1], W[i-1]
    std::copy_n(dp[pi].begin(), MAXL+1, dp[i].begin());
    // use V[i-1], W[i-1];
    for(int w = MAXL; w >= W[i-1]; --w) {
      int nv = dp[pi][w-W[i-1]] + V[i-1];
      if(nv > dp[i][w]) dp[i][w] = nv;
    }
  }
  int sumv[512], sumw[512];
  sumv[0] = sumw[0] = 0;
  int Q; std::cin >> Q;
  for(int q = 0; q < Q; ++q) {
    int u, L; std::cin >> u >> L;
    if(u < pN) {
      std::cout << dp[u][L] << "\n";
      continue;
    }
    std::vector<int> nodes;
    while(u >= pN) {
      nodes.push_back(u);
      u /= 2;
    }
    int ans = dp[u][L];
    int S = (1<<nodes.size());
    for(int s = 1; s < S; ++s) {
      int m = msb_(s);
      sumv[s] = sumv[s^(1<<m)] + V[nodes[m]-1];
      sumw[s] = sumw[s^(1<<m)] + W[nodes[m]-1];
      if(sumw[s] > L) continue;
      ans = std::max(ans, sumv[s] + dp[u][L - sumw[s]]);
    }
    std::cout << ans << "\n";
  }
  return 0;
}


Measured memory_bytes: 206440
N,M = map(int,input().split())

a = [0] * M
b = [0] * M

for i in range(M):
    a[i],b[i] = map(int,input().split())
    a[i] -= 1
    b[i] -= 1

count = 0
for k in range(M):
    con = [[] for _ in range(N)]
    for i in range(M):
        if i != k:
            con[a[i]].append(b[i])
            con[b[i]].append(a[i])
    visited = [0] * N
    stack = [[0,0]]
    while stack:
        cur,pre = stack.pop()
        if visited[cur] == 1:
            continue
        visited[cur] = 1
        for x in con[cur]:
            if x != pre:
                stack.append([x,cur])
    #print(visited)
    if 0 in visited:
        count += 1

print(count)
    

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

int main(){
         int n=0;
         cin >> n;
         vector <long > a (3*n);
         for (int i=0;i<3*n;i++) cin >> a[i];
         stable_sort(a.begin(),a.end());
         long long ans=0;
         for (int i=1;i<=n;i++){
                  ans+=a[3*n-i*2];
         }
         cout << ans;
}


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

using VI = vector<int>;
using VVI = vector<VI>;
using PII = pair<int, int>;
using LL = long long;
using VL = vector<LL>;
using VVL = vector<VL>;
using PLL = pair<LL, LL>;
using VS = vector<string>;

#define ALL(a)  begin((a)),end((a))
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define EB emplace_back
#define MP make_pair
#define SZ(a) int((a).size())
#define SORT(c) sort(ALL((c)))
#define RSORT(c) sort(RALL((c)))
#define UNIQ(c) (c).erase(unique(ALL((c))), end((c)))

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

#define FF first
#define SS second

#define DUMP(x) cout<<#x<<":"<<(x)<<endl
template<class S, class T>
istream& operator>>(istream& is, pair<S,T>& p){
  return is >> p.FF >> p.SS;
}
template<class T>
istream& operator>>(istream& is, vector<T>& xs){
  for(auto& x: xs)
	is >> x;
  return is;
}
template<class S, class T>
ostream& operator<<(ostream& os, const pair<S,T>& p){
  return os << p.FF << " " << p.SS;
}
template<class T>
ostream& operator<<(ostream& os, const vector<T>& xs){
  for(unsigned int i=0;i<xs.size();++i)
	os << (i?" ":"") << xs[i];
  return os;
}
template<class T>
void maxi(T& x, T y){
  if(x < y) x = y;
}
template<class T>
void mini(T& x, T y){
  if(x > y) x = y;
}


const double EPS = 1e-10;
const double PI  = acos(-1.0);
const LL MOD = 1e9+7;

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

  int N;
  cin >> N;
  VI cs(N);
  cin >> cs;
  int Q;
  cin >> Q;
  VI xs(N);
  while(Q--){
	int t, x, d;
	cin >> t >> x >> d;
	--x;
	if(t == 1){
	  xs[x] += d;
	  if(xs[x] > cs[x]){
		cout << x+1 << endl;
		return 0;
	  }
	}
	else{
	  xs[x] -= d;
	  if(xs[x] < 0){
		cout << x+1 << endl;
		return 0;
	  }
	}
  }
  cout << 0 << endl;

  return 0;
}



Measured memory_bytes: 3232
// --------------
// Tejas Pandey  |
// 16 - 11 - 19  |
// ABC #145      |
// --------------

#include <bits/stdc++.h>
using namespace std;

#define mod 1000000007
#define vi vector<int>
typedef long long int ll;

int main (void)
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	int t = 1;
	//cin >> t;
	while(t--)
	{
		//cout << "Case #" << c-t << ": ";
		int n;
		cin >> n;
		string s;
		cin >> s;
		if(n&1){
			cout << "No";
		}
		else{
			for(int i = 0;i < n/2;i++)
				if(s[i] == s[n/2 + i]);
				else{
					cout << "No";
					return 0;
				}
			cout << "Yes";
		}
	}
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(n);++i)
#define rrep(i,n) for(int i=1;i<(n);++i)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
#define maxs(a, b) a = max(a, b)
#define mins(a, b) a = min(a, b)
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const ll linf = (ll)4e18;
const int inf = 1001001001;
const int mod = 1000000007;
typedef pair<ll, ll> PL;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	int x, y, z, k;
	cin >> x >> y >> z >> k;
	vector<ll> a(x), b(y), c(z);
	rep(i, x) cin >> a[i];
	rep(i, y) cin >> b[i];
	rep(i, z) cin >> c[i];
	sort(rall(a));
	sort(rall(b));
	sort(rall(c));
	priority_queue<tuple<ll, int, int, int>> que;
	set<tuple<int, int, int>> done;
	que.emplace(a[0] + b[0] + c[0], 0, 0, 0);
	auto maybe_push = [&](int ai, int bi, int ci) -> void {
		auto tpl = make_tuple(ai, bi, ci);
		if (ai < x && bi < y && ci < z && !done.count(tpl)) {
			done.insert(tpl);
			que.emplace(a[ai] + b[bi] + c[ci], ai, bi, ci);
		}
	};
	int cnt = 0;
	while (que.size()) {
		ll sm = get<0>(que.top());
		int ai = get<1>(que.top());
		int bi = get<2>(que.top());
		int ci = get<3>(que.top());
		que.pop();
		cout << sm << endl;
		if (++cnt == k) break;
		maybe_push(ai + 1, bi, ci);
		maybe_push(ai, bi + 1, ci);
		maybe_push(ai, bi, ci + 1);
	}
	return 0;
}


Measured memory_bytes: 896
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;


// string^ÅÁZðs¢AÊðÔ·
string add(string &str1,string &str2){
  string str;
  int carry = 0;
  for(int i = 0; i < max(str1.size(),str2.size()); i++){
    if(i >= str1.size()){
      int ret = carry + str2[str2.size()-1-i] - '0';
      carry = ret / 10;
      str += (ret % 10) + '0';
    }
    else if(i >= str2.size()){
      int ret = carry + str1[str1.size()-1-i] - '0';
      carry = ret / 10;
      str += (ret % 10) + '0';
    }
    else{
      int ret = str1[str1.size()-1-i] + str2[str2.size()-1-i] - '0' - '0' + carry;
      carry = ret / 10;
      str += (ret % 10) + '0';
    }
  }
  str+=(carry+'0');
  // jóIÏX
  reverse(str.begin(),str.end());
  // æªÌ0ðÁ·
  int idx;
  for(int i = 0; i < str.size(); i++){
    idx=i;
    if(str[i]!='0'||str.size()-1==i)
      break;
  }
  return str.substr(idx);
}

int main(){

	int n;
	cin>>n;
	for(int i = 0; i < n; i++){
		string s1,s2;
		cin>>s1>>s2;
		if(s1.size()>80||s2.size()>80){
			cout<<"overflow"<<endl;
		}
		else{
			string ret=add(s1,s2);
			if(ret.size()>80){
				cout<<"overflow"<<endl;
			}
			else
				cout<<ret<<endl;
		}
	}

	return 0;
}

Measured memory_bytes: 0
#include <bits/stdc++.h>
#define rep(i, a, n) for(int i = a; i < n; i++)
#define REP(i, n) rep(i, 0, n)
#define repb(i, a, b) for(int i = a; i >= b; i--)
#define all(a) a.begin(), a.end()
#define int long long
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
typedef pair<int, int> P;
const int mod = 1000000007;
const int INF = 1e12;

int d[10010][110];
int sum[10010];

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n, m;
    cin >> n >> m;
    string s;
    rep(i, 0, m){
        cin >> s;
        rep(j, 0, n){
            d[j][i] = (s[j] == 'W' ? 1 : 0);
        }
    }
    sum[0] = 0;
    rep(i, 0, n){
        rep(j, 0, m){
            sum[i + 1] += d[i][j];
        }
    }
    rep(i, 0, n){
        sum[i + 1] += sum[i];
    }
    int ans = -1, MIN = INF;
    rep(i, 0, n + 1){
        int left = m * i - sum[i];
        int right = sum[n] - sum[i];
        int tmp = left + right;
        // cout << i << ' ' << left << ' ' << right << endl;
        if(tmp < MIN){
            MIN = tmp; ans = i;
        }
    }
    cout << ans << " " << ans + 1 << endl;
}


Measured memory_bytes: 11896