akhauriyash/Code-Regression huggingface dataset:
from collections import deque
from heapq import heapify,heappop,heappush,heappushpop
from copy import copy,deepcopy
from itertools import product,permutations,combinations,combinations_with_replacement
from collections import defaultdict,Counter
from bisect import bisect_left,bisect_right
from math import gcd,ceil,floor,factorial
# from fractions import gcd
from functools import reduce
from pprint import pprint
from statistics import mean,median,mode

INF = float("inf")

def mycol(data,col):
    return [ row[col] for row in data ]

def mysort(data,col,reverse_flag):
    data.sort(key=lambda x:x[col],reverse=reverse_flag)
    return data

def mymax(data):
    M = -1*float("inf")
    for i in range(len(data)):
        m = max(data[i])
        M = max(M,m)
    return M

def mymin(data):
    m = float("inf")
    for i in range(len(data)):
        M = min(data[i])
        m = min(m,M)
    return m

def mycount(ls,x):
    # lsはソート済みであること
    l = bisect_left(ls,x)
    r = bisect_right(ls,x)
    return (r-l)

def myoutput(ls,space=True):
    if space:
        if len(ls)==0:
            print(" ")
        elif type(ls[0])==str:
            print(" ".join(ls))
        elif type(ls[0])==int:
            print(" ".join(map(str,ls)))
        else:
            print("Output Error")
    else:
        if len(ls)==0:
            print("")
        elif type(ls[0])==str:
            print("".join(ls))
        elif type(ls[0])==int:
            print("".join(map(str,ls)))
        else:
            print("Output Error")

def I():
    return int(input())

def MI():
    return map(int,input().split())

def RI():
    return list(map(int,input().split()))

def CI(n):
    return [ int(input()) for _ in range(n) ]

def LI(n):
    return [ list(map(int,input().split())) for _ in range(n) ]

def S():
    return input()

def MS():
    return input().split()

def RS():
    return list(input())

def CS(n):
    return [ input() for _ in range(n) ]

def LS(n):
    return [ list(input()) for _ in range(n) ]

# ddict = defaultdict(lambda: 0)
# ddict = defaultdict(lambda: 1)
# ddict = defaultdict(lambda: int())
# ddict = defaultdict(lambda: list())
# ddict = defaultdict(lambda: float())

a,b,c = MI()

if a<c<b:
    print("Yes")
elif b<c<a:
    print("Yes")
else:
    print("No")

Measured memory_bytes: 77112
#include <bits/stdc++.h>
using namespace std;
using lnglng = long long;

void fnInput(lnglng& rnNumA, double& rnNumB)
{
  cin >> rnNumA >> rnNumB;
}

lnglng fnMultiple(lnglng nNumA, double nNumB)
{
  int nNumNB = nNumB * 100 + 0.5;
  return nNumA * nNumNB / 100;
}
  
int main()
{
  lnglng nNumA;
  double nNumB;

  fnInput(nNumA, nNumB);
  cout << fnMultiple(nNumA, nNumB) << endl;

  return 0;
}

Measured memory_bytes: 3724
m,a,b=gets.split.map(&:to_i),gets.split.map(&:to_i),gets.split.map(&:to_i)
m[2].times{($l||=[])<<a[(i=gets.split.map(&:to_i))[0]-1]+b[i[1]-1]-i[2]}
p [$l.min,a.min+b.min].min

Measured memory_bytes: 21148
N=int(input())
L=sorted(list(map(int,input().split())))
a=0
for i in range(N-2):
    for j in range(i+1,N-1):
        for k in range(j+1,N):
            if L[i]!=L[j] and L[j]!=L[k] and L[k]<L[i]+L[j]:
                a+=1
print(a)

Measured memory_bytes: 9184
fun main(args: Array<String>) {
    val (N, M) = listOfInt()
    val S = IntArray(M)
    val C = IntArray(M)
    repeat(M) {
        val (s, c) = listOfInt()
        S[it] = s - 1
        C[it] = c
    }
    var min = 0
    var max = 999
    when (N) {
        1 -> { min = 0; max = 9 }
        2 -> { min = 10; max = 99 }
        3 -> { min = 100; max = 999 }
    }
    fun d2c(D: Int): IntArray {
        var n = D
        val a = IntArray(N)
        for (i in (0 until N).reversed()) {
            a[i] = n % 10
            n /= 10
        }
        return a
    }
    for (n in min .. max) {
        var ans = true
        val d = d2c(n)
        for (m in 0 until M) {
            if (d[S[m]] != C[m]) ans = false
        }
        if (ans) {
            println(n)
            return
        }
    }
    println(-1)
}
fun next() = readLine()!!
fun nextInt() = Integer.parseInt(next())
fun listOfString() = next().split(" ")
fun listOfInt() = listOfString().map(String::toInt)


Measured memory_bytes: 38032
#include <iostream>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <math.h>
#include <map>
#include <queue>
#include <string>
using namespace std;

int n;
string s;

int main(){
	while(cin>>n){
		if(n==0)return 0;
		int t=1,f=2,r=3,ans=1;
		for(int i=0;i<n;i++){
			cin>>s;
			if(s=="North"){swap(t,f);f=7-f;}
			if(s=="East"){swap(t,r);t=7-t;}
			if(s=="West"){swap(t,r);r=7-r;}
			if(s=="South"){swap(t,f);t=7-t;}
			if(s=="Right"){swap(f,r);r=7-r;}
			if(s=="Left"){swap(f,r);f=7-f;}
			ans+=t;
		}
		cout<<ans<<endl;
	}
}

Measured memory_bytes: 0
macro_rules! get {
      ($t:ty) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.trim().parse::<$t>().unwrap()
          }
      };
      ($($t:ty),*) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              let mut iter = line.split_whitespace();
              (
                  $(iter.next().unwrap().parse::<$t>().unwrap(),)*
              )
          }
      };
      ($t:ty; $n:expr) => {
          (0..$n).map(|_|
              get!($t)
          ).collect::<Vec<_>>()
      };
      ($($t:ty),*; $n:expr) => {
          (0..$n).map(|_|
              get!($($t),*)
          ).collect::<Vec<_>>()
      };
      ($t:ty ;;) => {
          {
              let mut line: String = String::new();
              std::io::stdin().read_line(&mut line).unwrap();
              line.split_whitespace()
                  .map(|t| t.parse::<$t>().unwrap())
                  .collect::<Vec<_>>()
          }
      };
      ($t:ty ;; $n:expr) => {
          (0..$n).map(|_| get!($t ;;)).collect::<Vec<_>>()
      };
}

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

fn main() {
    input! {
        n: i32,
        A: [f64; n],
    }

    let mut ans = 0_f64;
    for a in A {
        ans += 1_f64 / a;
    }

    println!("{}", 1_f64 / ans);
}


Measured memory_bytes: 4352
n = int(input())
al = list(map(int,input().split()))
bl = list(map(int,input().split()))

k = sum(bl) - sum(al)

def ceil(a, b):
   return a // b + (a % b > 0)

up = 0
down = 0
for a, b in zip(al,bl):
    if b - a > 0:
        up += ceil(b-a, 2)
        down = (b-a) % 2
    else:
        down = (a-b)

if k >= up and k >= down:
    print("Yes")
else:
    print("No")

Measured memory_bytes: 4600
from collections import Counter
from collections import defaultdict
N = int(input())
S = [Counter(input()) for _ in range(N)]
c = defaultdict(lambda: 999999999)
for s in S:
    for ch in "abcdefghijklmnopqrstuvwxyz":
        if ch in s:
            c[ch] = min(c[ch], s[ch])
        else:
            c[ch] = 0
ans = ""
for ch in "abcdefghijklmnopqrstuvwxyz":
    ans = "".join([ans, ch * c[ch]])
print(ans)

Measured memory_bytes: 39920
import itertools
n,m,q = map(int,input().split())
li = []
for _ in range(q):
    li.append(list(map(int,input().split())))
kumi = list(itertools.combinations_with_replacement(range(1,m+1), n))
score = 0
for k in kumi:
    each_score = 0
    for l in li:
        a = l[0]
        b = l[1]
        diff = l[2]
        katen = l[3]
        if k[b-1]-k[a-1] == diff:
            each_score += katen
    if each_score > score:
        score = each_score
print(score)

Measured memory_bytes: 21604
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O0")
typedef long long int ll;
typedef long double ld;
#define rep(i,n) for (ll i = 0; i < (n); ++i)
const ll mod = 1e9+7;
const ll INF = 1e18;
#define All(a) (a).begin(),(a).end()
#define Pi acos(-1)

int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  cout << setprecision(15) << fixed;
  chrono::system_clock::time_point start,end;
  start = chrono::system_clock::now();

  ll a, b;
  cin >> a >> b;
  cout << (a+b)%24 << '\n';

  end = chrono::system_clock::now();
  auto elapsed = chrono::duration_cast< chrono::milliseconds >(end - start).count();
  cerr << elapsed << "ms" << '\n';
}

Measured memory_bytes: 3620
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a,b,c,d,i,j,k;

    float hudai,hudai2;
    int x[1002];

    while(1)

    {
        double sum=0;
        double avg=0;
        double total=0;
        double devt=0;
        cin>>a;
        if(a==0)
        {
            break;
        }

        for(i=0; i<a; i++)
        {
            cin>>x[i];
            sum=sum+x[i];
        }
        hudai2=a*1.0;
        avg=(sum/a);


        for(i=0; i<a; i++)
        {
            total=total+((x[i]-avg)*(x[i]-avg));
        }
        hudai=total/a;
        devt=sqrt(hudai);

        printf("%.8f\n",devt);
    }
    return 0;
}



Measured memory_bytes: 3212
N, K = map(int, input().split())
H = list(map(int, input().split()))

#dp[足場i]=足場iにたどり着く最小コスト
dp = [10**10 for _ in range(N+10)]

dp[0] = 0
for i in range(N):
    for k in range(1,min(K+1,N-i)):
        dp[i+k] = min(dp[i+k], dp[i] + abs(H[i]-H[i+k]))

print(dp[N-1])


Measured memory_bytes: 56544
#include <stdio.h>

long gojo(long a, long b){
  if(a % b)
    return gojo(b, a%b);
  else
    return b;
}

int main(){
  int n;  scanf("%d", &n);
  long ans = 1;

  do{
    long t;  scanf("%ld", &t);
    ans = ans / gojo(ans, t) * t;
  }while(--n);

  printf("%ld\n", ans);

  return 0;
}


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

int main() {
  int N,M;
  cin >> N >> M;
  vector<int> city(N,0);
  
  for ( int i=0; i < M; i++){
    int a,b;
    cin >> a >> b;
    city[a-1]++;
    city[b-1]++;   
  }
  for (int j=0; j < N; j++){
    cout << city[j] << endl;
  }
  
}


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

constexpr int inf = 0x3f3f3f3f;
constexpr ll linf = 0x3f3f3f3f3f3f3f3fLL;

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

    string s; cin >> s;
    int n = s.length();

    int ans = 0;
    for (int i = 0; i < n; i++) {
        if (i < (n + 1) / 2 && s[i] == 'p') ans--;
        if (i >= (n + 1) / 2 && s[i] == 'g') ans++;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 512
#include <cstdio>
#include <cmath>
#include <cstring>
#include <ctime>
#include <cassert>

#include <iostream>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>

using namespace std;

// defines
#define rrep(i, a, N) for (i=(N)-1;i>=(a);i--)
#define rep(i, a, N) for (i=(a);i<(N);i++)
#define sqr(x) (x) * (x)
#define all(v) (v.begin(), v.end())
#define pb push_back
#define random (rand() << 16 ^ rand())

// Typedefs
typedef pair<int, int> ii;

// constants
const int64_t inf = 1e18+7;
const int64_t mod = 1e9+7;


int main() {
	std::ios::sync_with_stdio(false);
	int A, B;

	cin >> A >> B;

	cout << A*B - (A+B-1) << endl;

	return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<cmath>
#include<map>
#include<iomanip>
#define rip(i,n) for(int i=0;i<n;i++)
#define ll long long
#define lb long double
#define vec vector<int>
using namespace std;
int main() {
	int s, w;
	cin >> s >> w;
	if (w >= s)cout << "unsafe" << endl;
	else cout << "safe" << endl;
}

Measured memory_bytes: 3620
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;

int main() {
  ll n,m;
  cin >> n >> m;
  vector<string> a(n);
  vector<string> b(m);
  for(ll i=0;i<n;i++) {
    cin >> a[i];
  }
  for(ll i=0;i<m;i++) {
    cin >> b[i];
  }
  for(ll i=0;i<n-m+1;i++) {
    for(ll j=0;j<n-m+1;j++) {
      bool flag=true;
      for(ll k=j;k<j+m;k++) {
        if(a[k].substr(i,m)!=b[k-j]) {
          flag=false;
        }
      }
      if(flag) {
      cout << "Yes" << endl;
      return 0;
      }
    }
  }
  cout << "No" << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
#define rp(i, k, n) for (int i = k; i < n; i++)
using ll = long long;
using ld = double;

template<class T>inline bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>inline bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
const ll INF = 1ll << 60;
const ll MOD = 1e9 + 7ll;
const double PI=3.14159265358979323846;
 
int main() {
    int n, k;
    cin >> n >> k;
    int s = 0;
    vector<int> A;
    rp(i, 0, n) {
        int a; cin >> a;
        A.emplace_back(a);
        s+=a;
    }
    vector<int> div;
    for(int i = 2; i*i <= s; i++) {
        if(s%i==0) {
            div.emplace_back(i);
            div.emplace_back(s/i);
        }
    }
    div.emplace_back(s);
    int res = 1;
    for(auto d: div) {
        // printf("d = %d\n", d);
        vector<int> rem;
        for(auto a: A) rem.emplace_back(a%d);
        sort(rem.begin(), rem.end());
        vector<int> sum_p(n+1);
        vector<int> sum_m(n+1);
        rp(i, 0, n) sum_p[i+1] = sum_p[i] + rem[i];
        for(int i = n-1; i>=0; i--) sum_m[i] = sum_m[i+1] + d - rem[i];
        rp(i, 0, n+1) {
            if(sum_p[i] == sum_m[i]) {
                int sum = 0;
                rp(j, 0, i) sum+=rem[j];
                if(sum<=k) chmax(res, d); 
            }
        }   
    }
    cout << res << endl;
    return 0;
}

Measured memory_bytes: 3636
#include<bits/stdc++.h>
#define ll          long long
#define pb          push_back
#define c(P)        cout<<P<<"\n"
#define pii         pair<ll,ll>
#define mi          map<ll,ll>
#define mii         map<pii,ll>
#define F           first
#define S           second
#define sz(a)       (ll)(a.size())
#define cr(P)       cout<<P<<"\n";return;
#define mem(a,val)  memset(a,val,sizeof(a))
#define fr(i,x,n)   for(ll i=x;i<n;i++)
#define frr(i,x,n)  for(ll i=n-1;i>=x;i--)
using namespace std;


const ll N   =  500005;
const ll mod = 1e9 + 7;



void solve(){

  ll x=0,y=0,c=0,ans=0;
  ll n,m,k;
  string s;
  cin>>s;
  if(s[0] =='7' or s[1]=='7' or s[2]=='7'){
  	c("Yes");
  }
  
  else c("No");

}

signed main(){
     
  ios_base::sync_with_stdio(false);   
  cin.tie(NULL);
  //int T;cin >> T;while (T--)
  solve();
  return 0;
}


Measured memory_bytes: 3652
#include<iostream>
#include<vector>
#include<array>
#include<string>

int main()
{
	std::array<int, 26> count = {};
	for (auto& c : count)
	{
		c = 100;
	}
	int N;
	std::cin >> N;
	for (int i{}; i < N; ++i)
	{
		std::string str;
		std::cin >> str;
		std::array<int, 26> now = {};
		for (char c : str)
		{
			++now[c - 'a'];
		}
		for (int j{}; j < 26; ++j)
		{
			count[j] = std::min(count[j], now[j]);
		}
	}
	for (int i{}; i < 26; ++i)
	{
		for (int j{}; j < count[i]; ++j)
		{
			std::cout << char('a' + i);
		}
	}
	std::cout << std::endl;
}

Measured memory_bytes: 256
# -*- coding: utf-8 -*-
# 整数の入力
#a = int(input())
# スペース区切りの整数の入力
#b, c = map(int, input().split())
# 文字列の入力
#s = input()
# 出力
#print("{} {}".format(a+b+c, s))

N = int(input())
ans = 'second'
for i in range(0, N):
    a = int(input())
    if a % 2 == 1:
        ans = 'first'
        break
print("{}".format(ans))


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

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

    int max = -1;
    int max2 = -1;

    vector<int> data(n);
    for (int i = 0; i < n; i++){
        int tmp;
        cin >> tmp;
        data.at(i) = tmp;
        if (max < tmp){
            max = tmp;
        }else if (max2 < tmp){
            max2 = tmp;
        }
    }

    for (int i = 0; i < n; i++){
        cout << (data.at(i) != max ? max : max2) << endl;
    }
}


Measured memory_bytes: 2432
import sys
input = sys.stdin.readline

n = int(input())
h = list(map(int, input().split()))
dp=[0]*n
dp[1]=abs(h[0]-h[1])
for i in range(2,n):
    dp[i]=min(dp[i-1]+abs(h[i]-h[i-1]),dp[i-2]+abs(h[i]-h[i-2]))
print(dp[-1])


Measured memory_bytes: 50288
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,a) for(int i=0;i<(a);i++)
const ll MOD=1000000007;
//const ll MOD=998244353;

int main(){
  string S; cin>>S;
  string T="",U="";
  for(int i=0;i<(S.length()-1)/2;i++) T+=S[i];
  for(int i=(S.length()+1)/2;i<S.length();i++) U+=S[i];
  int N=T.length();
  for(int i=0;i<N/2;i++){
    if(T[i]!=T[N-1-i]){
      cout<<"No\n";
      return 0;
    }
    if(U[i]!=U[N-1-i]){
      cout<<"No\n";
      return 0;
    }
  }
  for(int i=0;i<N;i++){
    if(T[i]!=U[N-1-i]){
      cout<<"No\n";
      return 0;
    }
  }
  cout<<"Yes\n";
  return 0;
}

Measured memory_bytes: 256
#include <iostream>
using namespace std;
int main(void){
  int a, b, c, num;
  cin >> num;
  
  for(int i = 0; i < num; i++) {
    cin >> a >> b >> c;
    if(a < b) {
      int temp = a;
      a = b;
      b = temp;
    }
    if(a < c) {
      int temp = a;
      a = c;
      c = temp;
    }
    
    if(a * a == b * b + c * c) {
      cout << "YES" << endl;
    } else {
      cout << "NO" << endl;
    }
  }
}

Measured memory_bytes: 3068
# coding: utf-8

#素因数分解
def prime_factorize(N):
    f = {}
    i = 2
    while i * i <= N:
        if N % i != 0:
            i += 1
            continue
        #指数
        exp = 0
        #割れる限り割り続ける
        while N % i == 0:
            exp += 1
            N //= i
        #結果をpush
        f[i] = exp
        #次の素数へ: 合成数は順次消されている
        i += 1
    #最後残った数について
    if N != 1:
        f[N] = 1
    return f

#main
N, P = map(int, input().split())
F = prime_factorize(P)
ans = 1
for i in F:
    ans *= i**(F[i]//N)
print(ans)

Measured memory_bytes: 9212
// abc132d.cpp : Blue and Red Balls
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

#define rep(i,n) for(int i=0;i<(n);i++)
#define upto(i,s,e,d) for(int i=(s);i<(e);i+=(d))
#define oute(x) cout<<(x)<<endl

const ll MOD = 1000000007;
ll c[2001][2001];

void init(int N){
  rep(i,N+1) rep(j,N-i) c[i][j] = (i==0 || j==0)? 1: (c[i][j-1] + c[i-1][j]) % MOD;
}

ll comb(int n, int r){
  if(n<r) return 0;
  return c[n-r][r];
}

int main(){
  int N,K; cin>>N>>K;
  int red = N-K, blue = K;
  init(N+1);
  upto(i,1,blue+1,1) oute((comb(red+1, i) * comb(blue-1, i-1)) % MOD);
}

Measured memory_bytes: 31104
#include <iostream>
#include <complex>
#include <sstream>
#include <string>
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <limits>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
#define REP(i, j) for(int i = 0; i < (int)(j); ++i)
#define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define REVERSE(v) reverse((v).begin(), (v).end())
typedef complex<double> P;
 
int main() {
  int N, K, P; cin >>N;
  while(N--){
    cin >>K >>P;
    K--;
    K %= P;
    cout <<K + 1 <<endl;
  }
  return 0;
}

Measured memory_bytes: 1160
import Data.List
main :: IO ()
main = do
  n <- getLine
  s <- getLine
  putStrLn $ show $ solve (filter (\x -> 2 <= length x) (group $ reverse $ sort $ map read $ words s)) (read n)

solve :: [[Int]] -> Int -> Int
solve ls n
  | n <= 4 && ls == [] || (length ls < 2) = 0
  | otherwise = if 4 <= length (head ls)  then (head (head ls)) * (head (head ls)) else (head $ head ls) * (head (ls!!1) )

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

const long long MOD = 1000000007;
const long long INF = 1LL << 60;
const int INT_INF = 1000000000;

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

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  int N, K;
  cin >> N >> K;
  vector<int> D(K);
  for (int i = 0; i < K; i++)
    cin >> D[i];
  while (1)
  {
    bool ok = true;
    string NS = to_string(N);
    for (int i = 0; i < NS.size(); i++)
    {
      for (int j = 0; j < D.size(); j++)
      {
        if (NS[i] == D[j] + '0')
          ok = false;
      }
    }
    if (ok)
      break;
    else
      N++;
  }
  cout << N << endl;
  return 0;
}


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

using namespace std;

#define fi first
#define se second
#define eb emplace_back
#define mt make_tuple
#define all(x) (x).begin(), (x).end() 
#define MOD 1000000007

typedef long long ll;
typedef pair <int, int> ii;
typedef pair <ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef long double ld;

const ll INF=LLONG_MAX;
const int mxn=55;
using T = tuple<int,ll,ll>;
int n,m,s;
ll ctr[mxn],tsct[mxn],dist[mxn][2505];
vector<T>adj[mxn];

struct state{
	int u; ll c,t;
	state(int u, ll c, ll t):u(u),c(c),t(t){};
	bool operator>(const state &s)const{return t>s.t;}
};

void dij(){
	for(int i=0; i<n; i++)
		for(int j=0; j<2505; j++)
			dist[i][j]=INF;
	
	priority_queue<state,vector<state>,greater<state>>pq;
	dist[0][s]=0LL;
	pq.push(state(0,s,0));
	while(!pq.empty()){
		state cur = pq.top(); pq.pop();
		for(T x:adj[cur.u]){
			int v; ll c,w;
			tie(v,c,w)=x;
			if(cur.c-c<0)continue;
			if(dist[v][cur.c-c]>dist[cur.u][cur.c]+w){
				dist[v][cur.c-c]=dist[cur.u][cur.c]+w;
				pq.push(state(v,cur.c-c,dist[v][cur.c-c]));
			}
		}
		if(cur.c+ctr[cur.u]<=2500){
			if(dist[cur.u][cur.c+ctr[cur.u]]>dist[cur.u][cur.c]+tsct[cur.u]){
				dist[cur.u][cur.c+ctr[cur.u]]=dist[cur.u][cur.c]+tsct[cur.u];
				pq.push(state(cur.u,cur.c+ctr[cur.u],dist[cur.u][cur.c+ctr[cur.u]]));
			}
		}
	}
}

int main()
{
    ios_base::sync_with_stdio(0); cin.tie(0);
    //freopen("input.txt","r",stdin); freopen("output.txt","w",stdout);
	cin >> n >> m >> s;
	s=min(s,2500);
	int u,v,a,b;
	for(int i=0; i<m; i++){
		cin >> u >> v >> a >> b;
		u--; v--;
		adj[u].eb(v,a,b);
		adj[v].eb(u,a,b);
	}
	for(int i=0; i<n; i++)cin >> ctr[i] >> tsct[i];
	dij();
	vll ans(n,INF);
	for(int i=1; i<n; i++)
		for(int j=0; j<2505; j++)
			ans[i]=min(ans[i],dist[i][j]);
	for(int i=1; i<n; i++)
		cout << ans[i] << endl;
}
	
// READ & UNDERSTAND
// ll, int overflow, array bounds, memset(0)
// special cases (n=1?), n+1 (1-index)
// do smth instead of nothing & stay organized
// WRITE STUFF DOWN


Measured memory_bytes: 7376
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
  //priorityqueueだとすると？N*M*Nとかむりそう
  //つどlower_bound+eraseかな
  //つどよりも全部BCだしきったほうがはやいな
  //TLE。。上書きしてみたけどTLE
  //sortが重そう
  //原型からどこまで数字をかえるのか。
  //1,2,3,4,5,6,7,8,9,10
  //5が3
  //4が10とかきたら
  //4こ交換候補、３つかえる
  //4,5,6,7,8,9,10,5,5,5にするとか。５以上は今後でないわけで
  //eraseが文末以外だと超重いっぽい。それを解消したい。
  //remove_ifを使いたいが、条件にZの値を引き継げない
  //なんかTLE抜けない･･･。配列２つ用意しようかなあ・・・
  ll N,M;
  cin>>N>>M;
  vector<ll>Z(N,0),X(0,0);
  for(int i=0; i<N; i++){
    ll A; cin>>A; Z[i]=A;
  }
  sort(Z.begin(),Z.end());
  vector<vector<ll>> D(M,vector<ll>(2,0));  
  ll pos=0;
  for(int i=0; i<M; i++){
    ll B,C; cin>>B>>C; D[i][0]=B, D[i][1]=C;
  }
  sort(D.begin(), D.end(), [](auto& x, auto& y){return x[1] > y[1];});
  for(int i=0; i<M; i++){
    ll ud=lower_bound(Z.begin(), Z.end(), D[i][1])-(Z.begin()+pos);
    ud=min(max(ud,0LL),D[i][0]);
    pos+=ud;
    if(ud==0) break;
    while(--ud>=0)
      X.emplace_back(D[i][1]);
  }
  ll ans=0,xs=X.size();
  for(int i=pos; i<N; i++)
    ans+=Z[i];
  for(int i=0; i<xs; i++)
    ans+=X[i];
  cout<<ans<<endl;
}

Measured memory_bytes: 7672
#define _USE_MATH_DEFINES
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
#include <complex>
#include <cmath>
#include <numeric>
#include <bitset>
#include <functional>

using namespace std;

#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << ": " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << ": " << arg1 << " |";
  __f(comma + 1, args...);
}

typedef long long int64;
typedef pair<int, int> ii;
const int INF = 1 << 29;
const int MOD = 1e9 + 7;

int main() {
  int n, a, b;
  cin >> n >> a >> b;
  cout << min(n * a, b) << endl;
  return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll,ll> mp;
ll inf =  1e9;


int main(){
    ll a,b;
    cin>>a>>b;
    ll res = 0;
    b--;
    cout<<b/(a-1) + ( b%(a-1) != 0) << endl;

    return 0;
}


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

ans = []

for i in range(n+1):#1000円
    for j in range(n+1-i):#5000円
        val = 1000 * i + 5000 * j + 10000 * (n-i-j)
        if val == y:
            ans.append(n-i-j)
            ans.append(j)
            ans.append(i)
            break

if ans:
    print(*ans[0:3])
else:
    print(-1,-1,-1)

Measured memory_bytes: 3064
#include <algorithm>
#include <array>
#include <deque>
#include <functional>
#include <iostream>
#include <math.h>
#include <numeric>
#include <vector>
#define ll long long int
#define FOR(i, a, b) for (ll i = (ll)(a); i < (ll)(b); i++)
#define REP(i, n) FOR(i, 0, n)
#define REP1(i, n) FOR(i, 1, n)

using namespace std;

int main() {
    ll n, m, k;
    cin >> n >> m >> k;
    ll a[n], b[m], pa[n + 1], pb[m + 1];
    pa[0] = 0;
    pb[0] = 0;
    REP(i, n) {
        cin >> a[i];
        pa[i + 1] = a[i] + pa[i];
    }
    REP(i, m) {
        cin >> b[i];
        pb[i + 1] = b[i] + pb[i];
    }

    ll ans = 0;
    ll checkpoint_b = m;
    REP(i, n + 1) {
        if (pa[i] > k)
            break;
        while (pb[checkpoint_b] > k - pa[i]) {
            checkpoint_b--;
        }
        ans = max(ans, i + checkpoint_b);
    }
    cout << ans << endl;
}


Measured memory_bytes: 9852
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=2019;
int main() {
#ifndef ONLINE_JUDGE
	freopen("input1.txt","r",stdin);
	freopen("output1.txt","w",stdout);
#endif
	ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    string s;
    ll n,ans=0,i,suf=0,p=1;
    cin>>s;
    n=s.length();
    vector<ll>mp(mod+3);
    mp[0]++;
    for(i=n-1;i>=0;i--){
    	int dig=s[i]-'0';
    	suf=((suf%mod)+((p*dig)%mod))%mod;
    	p=(p*10)%mod;
    	ans+=mp[suf];
    	mp[suf]++;
    }
    cout<<ans<<"\n";
}

Measured memory_bytes: 3788
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <set>
#include <cmath>
#include <bitset>
#include <iomanip> 

using ll = long long;
using ull = unsigned long long;
using namespace std;

#define FALSE printf("false\n");
#define TRUE printf("true\n");
#define all(x) (x).begin(),(x).end()
#define rep(i,n) for(int i = 0;(i) < ((int)(n));++(i))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() )
#define test(a) cout<<"line:"<<__LINE__<<"["<<(#a)<<": "<<(a)<<"]"<<endl

const int INF = 1e9+7;
const ll INFL = 9*1e18;

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

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

ll inline digit(ll num){int tmp = 0;while(num){tmp++;num/=10;}return tmp;} // 桁数
template<typename T>inline void print(T&& x){cout<<x<<endl;}// 改行付き出力
template<typename T>inline T SUM(vector<T> vec){return accumulate(all(vec),(T)0);} // vectorの中身を全部足す
template<typename T>inline T digitSum(T num){T sum = 0;while(num){sum+=num%10;num/=10;}return sum;} // 各桁の和
template<typename T>inline T gcd(T a,T b){if(b == 0)return a;return gcd(b,a%b);} // 最大公約数
template<typename T>inline T lcm(T a, T b){T g = gcd(a,b);return a/g*b;} // 最小公倍数
template<typename T>inline T power(T a,T b){T tmp=1;rep(i,b){tmp*=a;}return tmp;} // 累乗
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
int ctoi(char c){return c-'0';}


// TODO: write
int main() {
  int n;cin>>n;
  vector<string> a(n);rep(i,n)cin>>a[i];
  map<string,int> m;
  rep(i,n){
    m[a[i]]++;
  }
  cout<<"AC x "<<m["AC"]<<endl;
  cout<<"WA x "<<m["WA"]<<endl;
  cout<<"TLE x "<<m["TLE"]<<endl;
  cout<<"RE x "<<m["RE"]<<endl;
  return 0;
}

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

int main()
{
  int n;
  scanf("%d",&n);
  static long long a[100000];
  for(int i=0;i<n;i++){
    scanf("%lld",a+i);
  }
  int c=0,ans=0;
  for(int i=0;i<n;i++){
    int t=0;
    while(a[i]>(1ll<<t)){
      t++;
    }
    //printf("%d %d\n",c,t);
    if(a[i]%(1ll<<c)==0){
      ans+=t-c;
      c=t;
    }
    else if(a[i]==(1ll<<t)){
      c=t;
    }
    else if(c<=t-1){
      ans+=t-c;
      c=t;
    }
    else{
      c=t-1;
    }
  }
  printf("%d\n",ans);
  return 0;
}


Measured memory_bytes: 1024
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <vector> 
#include <numeric>
#include <cmath>
#include <queue>


#define CHMAX(a,b) a = std::max(a,b)
#define CHMIN(a,b) a = std::min(a,b)
#define CHABS(a) a = std::abs(a) 
#define COUT(a) std::cout << a << std::endl
#define CERR(a) std::cerr << a << std::endl
#define FOR(n) for(lli i = 0; i < n; i++)

using namespace std;
using lli = long long int;
using pll = pair<lli, lli>;
using tlll = tuple<lli, lli, lli>;

lli mod197 = 1000000007LL;

// ax + by = gcd(a,b) 最大公約数
template< typename T >
T extgcd(T a, T b, T& x, T& y) {
	T d = a;
	if (b != 0) {
		d = extgcd(b, a % b, y, x);
		y -= (a / b) * x;
	}
	else {
		x = 1;
		y = 0;
	}
	return d;
}

int main(void) {

  int a,b;
  cin>>a>>b;
  if(b%a==0) COUT(b+a);
  else COUT(b-a);
  
	return 0;
}


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

inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}

typedef long long ll;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<long long> VL;
typedef vector<vector<long long>> VVL;
typedef vector<string> VS;
typedef pair<int, int> P;
typedef tuple<int,int,int> tpl;

#define ALL(a)  (a).begin(),(a).end()
#define SORT(c) sort((c).begin(),(c).end())
#define REVERSE(c) reverse((c).begin(),(c).end())
#define LB(a,x) lower_bound((a).begin(), (a).end(), x) - (a).begin()
#define UB(a,x) upper_bound((a).begin(), (a).end(), x) - (a).begin()

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

#define en "\n"

constexpr double EPS = 1e-9;
constexpr double PI  = 3.1415926535897932;
constexpr int INF = 2147483647;
constexpr long long LINF = 1LL<<60;
constexpr long long MOD = 1000000007; // 998244353;

#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

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; }

void Main(){
    int N; cin >> N;
    VI A(N), B(N); REP(i,N) cin >> A[i]; REP(i,N) cin >> B[i];

    priority_queue<P> q;
    REP(i,N) q.emplace(B[i],i);

    ll ans = 0;
    while(q.size()){
        int i = q.top().second; q.pop();
        if(B[i] == A[i]) continue;
        int u = i>0 ? i-1 : N-1, v = i, w = (i+1)%N;
        int mx = max(B[u],B[w]);
        if(mx >= B[v]){
            cout << -1 << en;
            return;
        }
        int div = (B[v]-mx + B[u]+B[w]-1) / (B[u]+B[w]);
        if(B[u]==A[u] && B[w]==A[w]){
            if((B[v]-A[v])%(B[u]+B[w]) != 0){
                cout << -1 << en;
                return;
            }
            div = (B[v]-A[v]) / (B[u]+B[w]);
            ans += div;
            continue;
        }
        ans += div;
        B[v] -= div * (B[u]+B[w]);

        if(B[v] < A[v]){
            cout << -1 << en;
            return;
        }
        if(B[v] > A[v]) q.emplace(B[v],v);
    }
    cout << ans << en;
    return;
}

int main(void){
    cin.tie(0);ios_base::sync_with_stdio(0);cout<<fixed<<setprecision(15);
    int t=1; //cin>>t;
    REP(_,t){
        Main();
    }
    return 0;
}

Measured memory_bytes: 4084
import java.io.*;
import java.util.*;
import java.lang.Math.*;
public class Main{
    public static void main(String[] args)throws IOException{
	InputStreamReader isr = new InputStreamReader(System.in);
	BufferedReader br = new BufferedReader(isr);
	String line;
	while((line=br.readLine())!=null){
	    int hit=0,blow=0;
	    int[] a =new int[4];
	    int[] b =new int[4];
	    StringTokenizer st = new StringTokenizer(line);
	    for(int i = 0;i<4; i++){
		a[i]=Integer.parseInt(st.nextToken());
	    }
	    st = new StringTokenizer(br.readLine());
	    for(int i = 0;i<4;i++){
		b[i]=Integer.parseInt(st.nextToken());
	    }
	    for(int i = 0;i<4;i++){
		for(int j = 0;j<4;j++){
		    if(i==j&&a[i]==b[j]){
			hit++;
		    }
		    if(i!=j&&a[i]==b[j]){
			blow++;
		    }
		}
	    }
	    System.out.println(hit+" "+blow);
	}
    }
}
			

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

int main() {
	string s, t; cin >> s >> t;
	vector<int> c1('z' - 'a' + 1, 0), c2('z' - 'a' + 1, 0);
	for (int i = 0; i < s.size(); i++) {
		c1[s[i] - 'a']++;
		c2[t[i] - 'a']++;
	}
	sort(c1.begin(), c1.end());
	sort(c2.begin(), c2.end());
	for (int i = 0; i < 'z' - 'a' + 1; i++) {

		if (c1[i] != c2[i]) {
			cout << "No" << endl;
			return 0;
		}
	}
	cout << "Yes" << endl;
	return 0;

}

Measured memory_bytes: 776
import java.util.Scanner;

class Main {
	public static void main(String args[]){	
		Scanner scan = new Scanner(System.in);

		int n = scan.nextInt();
	
		int a[];
		a = new int[n];
		
		for(int i = 0;i < n;i++){
			a[i] = scan.nextInt();
		}
		
		for(int i = n-1;i >= 0;i--){
			System.out.print(a[i]);
			if(i!=0){
				System.out.print(" ");
			}
		}
		System.out.println();
	}
}

Measured memory_bytes: 26272
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n)     for(int i = 0; i < (int)(n); i++)
#define rep2(i, m, n) for(int i = m; i < (int)(n); i++)
#define MOD 1000000007
#define Graph vector<vector<int>>
#define lint int64_t

int main(){
    lint N,M;
    cin >> N >> M;
    

    lint tmpGCD = M / N;
    lint ans = 1;
    
    lint r,q;
    while(tmpGCD > 1){    
        r = M / tmpGCD;
        q = M % tmpGCD;

        if((q == 0) && (r >= N)){
            ans = tmpGCD;
            break;
        }
        tmpGCD--;
    }

    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <stdio.h>

using namespace std;

int main(){
	int n[12],N,p[12],pc[12],pp[12],t,c=0,flg;

	while(1){
		cin >> N;

		if(N==0)break;

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

		while(1){
			c++;
			flg=0;

			if(c==10)break;

			//initialize counter
			for(int j=0;j<N;j++){
				pc[j] = 0;
			}

			//count
			for(int i=0;i<N;i++){
				//pick up
				t = n[i];

				for(int j=0;j<N;j++){
					if(t==n[j]){
						pc[i]++;
					}
				}
			}

			//judge
			for(int i=0;i<N;i++){
				if(n[i]!=pc[i]){
					flg=1;
				}
			}

			//if made p[]
			if(flg==0){
				break;
			}

			for(int i=0;i<N;i++){
				n[i] = pc[i];
			}
		}

		c--;

		cout << c << endl;
		for(int i=0;i<N-1;i++){
			cout << pc[i] << " ";
		}
		cout << pc[N-1] << endl;

		c=0;
	}

	return 0;
}

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

int main() {
  int N;
  cin >> N;
  vector<int> L(N);
  for (int i = 0; i < N; i++) cin >> L[i];
  sort(L.begin(), L.end());
  int cnt = 0;
  for (int a = 0; a < N - 2; a++) {
    for (int b = a + 1; b < N - 1; b++) {
      int k = lower_bound(L.begin(), L.end(), L[a]+L[b]) - L.begin();
      cnt += k - b - 1;
    }
  }
  cout << cnt << endl;
}


Measured memory_bytes: 256
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		int b = scan.nextInt();
		int x = scan.nextInt();
		if(x<=a+b && a<=x) {
			System.out.println("YES");
		}else {
			System.out.println("NO");
		}
	}

}


Measured memory_bytes: 23764
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <map>
#include <set>
#include <utility>
#include <vector>

using namespace std;

int main(){
  int N;
  scanf("%d", &N);
  vector<int> p(N, 0);
  for (int i = 0; i < N; i++){
    scanf("%d", &(p[i]));
  }  
  vector<int> a(N, 0);
  vector<int> b(N, 0);
  for (int i = 0; i < N; i++){
    a[i] = 20000*i + 500000000;
  }
  for (int i = 0; i < N; i++){
    b[i] = 500000000-20000*i;
  }
  for (int i = 0; i < N; i++){
    b[p[i]-1] += i+1;
  }
  for (int i = 0; i < N; i++){
    printf("%d", a[i]);
    if (i == (N-1)){
      printf("\n");
    }else{
      printf(" ");
    }
  }
  for (int i = 0; i < N; i++){
    printf("%d", b[i]);
    if (i == (N-1)){
      printf("\n");
    }else{
      printf(" ");
    }
  }
  printf("\n");
  return 0;
}


Measured memory_bytes: 896
import java.io.*;
import java.util.*;

public class Main {

    static class Question {
        int N;
        
        public void main(FastScanner in, PrintWriter out) {
            N = in.nextInt();
            out.println( "ABC" + N );
        }
        
        public void p(Object o) { System.out.print(o); }
        public void pl(Object o) { System.out.println(o); }
        public void arp(int[] o) { pl( Arrays.toString(o) ); }
        public void arpp(int[][] o) { 
            for (int i = 0; i < o.length; i++) {
                for (int j = 0; j < o[0].length; j++) { p( o[i][j] + " " ); } pl("");
            }
        }
    }

    public static void main(String[] args) throws Exception {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Question q = new Question();
        q.main(in, out);
        out.close();
        in.close();
    }
    
    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;
        public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); }
        public int nextInt() { return Integer.parseInt(next()); }
        public long nextLong() { return Long.parseLong(next()); }
        public double nextDouble() { return Double.parseDouble(next()); }
        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try { st = new StringTokenizer(br.readLine()); } 
                catch (IOException e) { e.printStackTrace(); }
            }
            return st.nextToken();
        }
        public void close() throws IOException { br.close(); }
    }
}


Measured memory_bytes: 22996
#include <algorithm>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <ctime>
#include <deque>
#include <iostream>
#include <list>
#include <map>
#include <memory.h>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long double LD;
typedef long long LL;
typedef pair<LL, LL> pll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#ifdef LOCAL
#define DEBUG(x) { cerr << "# " << #x << ": " << x << endl;}
#else
#define DEBUG(x)
#endif
mt19937_64 mt(time(0));
/*---------------------------------------------------------------------------------------------------
　　　　　　　　　　　 ∧＿∧
　　　　　 ∧＿∧ 　（´<_｀ ）　 Welcome to My Coding Space!
　　　　 （ ´_ゝ`）　/　 ⌒i
　　　　／　　　＼　 　  |　|
　　　 /　　 /￣￣￣￣/　　|
　 ＿_(__ﾆつ/　    ＿/ .| .|＿＿＿＿
　 　　　＼/＿＿＿＿/　（u　⊃
---------------------------------------------------------------------------------------------------*/
const int MAXN = 1e5 + 10;
const int MAXM = (1<<18) + 10;
int dp[567][MAXN];
int v[MAXM], w[MAXM];
vector<pii> cur;

int solve(int i, int m) {
  if (i <= m) return i;
  int n = cur.size();
  for (int j = 0; j < n; j++) {
    cur.emplace_back(cur[j].first+w[i], cur[j].second + v[i]);
  }
  return solve(i/2, m);
}

int main() {
  ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
  cout.precision(10); cout << fixed;
#ifdef LOCAL
  freopen("../test.txt", "r", stdin);
    // freopen("../output.txt", "w", stdout);
#endif
  int n; cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> v[i] >> w[i];
  }
  int m = min(n, 1<<9);
  for (int i = 1; i <= m; i++) {
    for (int j = 0; j < MAXN; j++) {
      dp[i][j] = dp[i/2][j];
      if (j-w[i] >= 0) dp[i][j] = max(dp[i][j], dp[i/2][j-w[i]] + v[i]);
    }
  }
  int q; cin >> q;
  while (q--) {
    int node, weight;
    cin >> node >> weight;
    cur.clear();
    cur.emplace_back(0, 0);
    node = solve(node, m);
    int ret = 0;
    for (const auto& item : cur) {
      if (item.first > weight) continue;
      ret = max(item.second + dp[node][weight-item.first], ret);
    }
    cout << ret << '\n';
  }






/*---------------------------------------Coding Space End------------------------------------------*/
#ifdef LOCAL
  cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s." << endl;
#endif
  return 0;
}
/* author:  txingml */
/* picture is from hamayanhamayan(CF handle) */


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

using namespace std;

#ifndef aa
#define trace(...)
#define endl '\n'
#endif
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define fi first
#define se second
#define int long long
typedef long long ll;
typedef long double ld;
#define double long double
#define pii pair<int,int>
#define pdd pair<double,double>
#define pll pair<ll,ll>
#define sz(x) ((long long)x.size())
#define fr(a,b,c) for(int a=b; a<=c; a++)
#define frev(a,b,c) for(int a=c; a>=b; a--)
#define rep(a,b,c) for(int a=b; a<c; a++)
#define trav(a,x) for(auto &a:x)
#define all(con) con.begin(),con.end()
#define deb(x) cout << x << endl
#define done(x) {cout << x << endl;return;}
const ll infl = 0x3f3f3f3f3f3f3f3fLL;
const int infi = 0x3f3f3f3f;
mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
//const int mod = 998244353;
const int mod = 1e9 + 7;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<pair<int, int>> vpii;
typedef map<int, int> mii;
typedef set<int> si;
typedef set<pair<int,int>> spii;
typedef queue<int> qi;


const int N = 1e5+5;
int f[N];

void solve() {

  int n,ans=0;
  cin>>n;
  vi a(n);
  rep(i,0,n)
    cin>>a[i], f[a[i]]++, ans+=a[i];
  int q;
  cin>>q;
  while(q--){
    int b,c;
    cin>>b>>c;
    ans+=f[b]*(c-b);
    f[c]+=f[b];
    f[b]=0;
    cout<<ans<<endl;
  }
}


signed main() {
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    //srand(chrono::high_resolution_clock::now().time_since_epoch().count());
    cout << fixed << setprecision(15);
    int t = 1;
   //cin >> t;

    while (t--)
        solve();
#ifdef aa
    cout << endl << endl << endl << endl << "Time elapsed: " << (double)(clock() - clk) / CLOCKS_PER_SEC << endl;
#endif
    return 0;
}







int powm(int a, int b) {
    int res = 1;
    while (b) {
        if (b & 1)
            res = (res*a) % mod;
        a = (a * a) % mod;
        b >>= 1;
    }
    return res;
}

int divide(int a, int b) {
    return (a % mod) * powm(b, mod - 2) % mod;
}

int norm(int a) {
    while (a >= mod) a -= mod;
    while (a < 0) a += mod;
    return a;
}


int gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}


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

class Program
{
    static void Main(string[] args)
    {
        var S = ReadLine();

        var ans = "Good";

        if (S[0] == S[1] || S[1] == S[2] || S[2] == S[3])
            ans = "Bad";

        WriteLine(ans);
    }
}


Measured memory_bytes: 25640
import math
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
dish = [a, b, c, d, e]
tmp = 10
for i in range(len(dish)):
    s = dish[i] % 10
    if s < tmp and s != 0:
        tmp = s
sum = 0
for i in range(len(dish)):
    sum += math.ceil(dish[i]/10.0)*10

print(sum - 10 + tmp)

Measured memory_bytes: 3064
#include <iostream>
#include <cstdio>
#include <algorithm>

#define reep(i,n,m) for(int i=(n);i<(m);i++)
#define rep(i,n) reep(i,0,n)

using namespace std;

int main(){
    int N;
    while(cin>>N,N){
        int a[40000];
        int b[40000];

        rep(i,N){
            scanf("%d",a+i);
        }
        rep(i,N){
            scanf("%d",b+i);
        }

        sort(a,a+N,greater<int>());
        sort(b,b+N,greater<int>());

        int win[40000] = {0};
        int a_i = 0;
        int cou = 0;
        int ans = -1;
        rep(b_i,N){
            while(a_i<N){
                if(a[a_i]<=b[b_i]){
                    win[a_i]++;
                    a_i++;
                    break;
                }
                a_i++;
            }
            cou += win[b_i];
            //printf("->%d\n",cou);

            if(b_i+1-cou>(b_i+1)/2){
                ans = b_i+1;
                break;
            }
        }
        if(ans==-1 || ans==N){
            puts("NA");
        }else{
            cout << ans << endl;
        }
    }
}

Measured memory_bytes: 1736
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.StringTokenizer;
class Main{
	public static void main(String[] args) {
		SC sc=new SC(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		int c=sc.nextInt();
		if(a==b && b==c && c==a) {
			pl("Yes");
		}
		else {
			pl("No");
		}
	}
	static class SC {
		private BufferedReader reader = null;
		private StringTokenizer tokenizer = null;
		public SC(InputStream in) {
			reader = new BufferedReader(new InputStreamReader(in));
		}
		public String next() {
			if (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new UncheckedIOException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
	public static void pl() {
		System.out.println();
	}
	public static void p(Object o) {
		System.out.print(o);
	}
}

Measured memory_bytes: 21076