akhauriyash/Code-Regression huggingface dataset:
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自動生成されたメソッド・スタブ
		
		Scanner scan = new Scanner(System.in);
		
		int n = scan.nextInt();
		long[] a = new long[n];

		for (int i = 0; i < n ;  i++) {
			a[i] = scan.nextLong();
			if(a[i] == 0) {				//入力された数値が0なら"0"を出力
				System.out.print(0);
				return;					//プログラム終了
			}
		}
		
		long ans = a[0];
		for(int i = 1; i < n; i++) {
			if(a[i] <= (1000000000000000000L / ans)) {
				ans *= a[i];
			}
			else {
				System.out.print(-1);
				return;
			}
		}
		
		System.out.print(ans);
		
	}

}


Measured memory_bytes: 61744
#include <algorithm>
#include <bitset>
#include <tuple>
#include <cstdint>
#include <cstdio>
#include <cctype>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <limits>
#include <map>
#include <memory>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#define ArraySizeOf(array)     (sizeof(array) / sizeof(array[0]))
#define res(i,n) for(int i=n;;i++)
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define REP(i,n) for(int i=1;i<n;i++)
#define rev(i,n) for(int i=n-1;i>=0;i--)
#define REV(i,n) for(int i=n-1;i>0;i--)
#define req(i,n,m) for(int i=n;i<m;i++)
#define REQ(i,n,m,l) for(int i=n;i<m;i+=l) 
#define _GLIBCXX_DEBUG
int INF = 1e9 + 7;
unsigned NthDayOfWeekToDay(unsigned n, unsigned dow, unsigned dow1)
{
    unsigned day;
    if (dow < dow1) dow += 7;
    day = dow - dow1;
    day += 7 * n - 6;
    return day;
}
signed gcd(long long x, long long y) {
    if (y == 0)return x;
    return gcd(y, x % y);
}
signed lcm(long long x, long long y) {
    return x / gcd(x, y) * y;
}
unsigned DayToWeekNumber(unsigned day)
{
    return (day - 1) / 7 + 1;
}
unsigned AnotherDayOfWeek(unsigned day, unsigned day0, unsigned dow0)
{
    return (dow0 + 35 + day - day0) % 7;
}
using namespace std;
signed main() {
    int N, L; cin >> N >> L;
    vector<string>S(N);
    rep(i, N)cin >> S[i];
    sort(S.begin(), S.end());
    rep(i, N) cout << S[i];
}

Measured memory_bytes: 3612
#include <bits/stdc++.h>
#define REP(i,a,b) for(int(i)=(a);(i)<(b);++(i))
#define RREP(i,a,b) for(int(i)=(a)-1;(i)>=(b);--(i))
#define ALL(x) (x).begin(),(x).end()
#define chmin(x,v) x = min(x, v)
#define chmax(x,v) x = max(x, v)
using namespace std;
typedef long long ll;

ll a, b, c;

int main()
{
  cin >> a >> b >> c;
  ll d = c - a - b;
  string res = (d > 0 && 4 * a * b < d * d) ? "Yes" : "No";
  cout << res << endl;

  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define MOD (long long int)(1e9+7)
#define ll long long int
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define reps(i,n) for(int i=1; i<=(int)(n); i++)
#define REP(i,n) for(int i=n-1; i>=0; i--)
#define REPS(i,n) for(int i=n; i>0; i--)
#define FOR(i,a,b) for(int i=a; i<(int)(b); i++)
#define ALL(x) (x).begin(),(x).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define CLR(a) memset((a), 0 ,sizeof(a))
#define PB push_back
#define MP make_pair
#define SP << " " <<
const int INF = 1001001001;
const ll LINF = 100100100100100100;
const double EPS = 1e-10;
const long double PI  = acos(-1.0L);
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef pair<double,double> PDD;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VL;
#define chmax(a,b) a = (((a)<(b))?(b):(a))
#define chmin(a,b) a = (((a)>(b))?(b):(a))

__attribute__((constructor))
void initial(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	cout << fixed << setprecision(15);
}


signed main(){
	int n,m; cin>>n>>m;
	VVI g; int h[n];
	rep(i,n){
		VI v; g.PB(v); h[i]=0;
	}
	int a[n+m-1],b[n+m-1];
	rep(i,n+m-1){
		cin>>a[i]>>b[i]; a[i]--; b[i]--; g[a[i]].PB(b[i]); h[b[i]]++;
	}
	stack<int> st; rep(i,n)if(h[i]==0) st.push(i);
	VI p;
	while(st.size()){
		int i=st.top(); st.pop();
		p.PB(i);
		for(auto& j: g[i]){
			h[j]--;
			if(h[j]==0) st.push(j);
		}
	}
	int rev[n]; rep(i,n) rev[p[i]]=i;
	// rep(i,n) cerr<<rev[i]<<' '; cerr<<endl;
	VI ans(n,p[0]); ans[p[0]]=-1;
	rep(i,n-1+m)if(rev[ans[b[i]]]<rev[a[i]]) ans[b[i]]=a[i];
	rep(i,n) cout<<ans[i]+1<<endl;


	return 0;
}


Measured memory_bytes: 9456
#include <bits/stdc++.h>
using namespace std;
using lint     = long long;
const lint inf = 1LL << 60;
const lint mod = 1000000007;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    bool ok = true;
    for (int i = 0; i < n; ++i) {
        if (a[i] % 2 == 0 && a[i] % 3 != 0 && a[i] % 5 != 0)
            ok = false;
    }
    if (ok)
        cout << "APPROVED"
             << "\n";
    else
        cout << "DENIED"
             << "\n";
    return 0;
}

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

int main(){
  string S;
  cin >> S;
  if(S=="Sunny"){
    cout << "Cloudy" << endl;
  }
  else if(S=="Cloudy"){
    cout << "Rainy" << endl;
  }
  else{
    cout << "Sunny" << endl;
  }
}

Measured memory_bytes: 256
/******************************************************************************

                              facts dont care about your feelings

*******************************************************************************/

#include <iostream>

#include<string>
using namespace std;

int main()
{
    char x;
    cin>>x;
    
    if(isupper(x)){
        cout<<"A"<<endl;
    }
    else{
        cout<<"a"<<endl;
    }

    return 0;
}


Measured memory_bytes: 3628
// -_-
#include <bits/stdc++.h>
#define pb push_back
#define fi first
#define se second
#define rz resize
#define fori(i, a, b) for(int i = a; i <= b; i++)
#define ford(i, a, b) for(int i = a; i >= b; i--)
#define mod 1000000007
 
using namespace std;
 
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef pair<int, int> pii;
typedef pair<long long , long long> pll;
 
int main() 
{

	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	ll n, k;
	cin >> n >> k;
	ll ans = 0;
	ll t = n-k;
	ans += (t*(t+1))/2;

	for(int i = k+1; i <= n-k; i++)
	{
		ll c = n/i - 1;
		ans += (c*(i-k));
		if(n%i >= k)
			ans += (n%i-k+1);
	}
	if(k == 0) ans -= n;
	cout << ans;

	return 0;
}

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

int main()
{

    int N;
    string S;
    cin >> N >> S;

    for (auto &&x : S)
    {
        x += N;

        if((int)x>90){
            x = 'a' + x - 'z'-1;
        }
    }

    cout << S << endl;
}

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

using namespace std;
using ll = long long int;

using Graph = vector<vector<int>>;

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

  int n;
  cin >> n;

  Graph g(n);
  vector<int> deg(n, 0);
  for (int i = 0; i < n; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    g[a].push_back(b);
    g[b].push_back(a);
    deg[a]++;
    deg[b]++;
  }

  int q;
  cin >> q;
  vector<pair<int, int>> queries;
  for (int _ = 0; _ < q; _++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    queries.push_back({a, b});
  }

  // シンクたちをキューに挿入する
  queue<int> que;
  for (int i = 0; i < n; i++) {
    if (deg[i] == 1)
      que.push(i);
  }

  vector<bool> cycle(n, true);
  while (!que.empty()) {
    int v = que.front();
    que.pop();
    cycle[v] = false;

    for (auto nv : g[v]) {
      deg[nv]--;
      if (deg[nv] == 1) {
        que.push(nv);
      }
    }
  }

  for (auto query : queries) {
    int a = query.first;
    int b = query.second;
    if (cycle[a] && cycle[b])
      cout << 2 << endl;
    else
      cout << 1 << endl;
  }

  return 0;
}



Measured memory_bytes: 9564
#include <cstdint>
#include <cmath>
#include <iostream>
#include <string>

using namespace std;

int main() {
  int K;
  cin >> K;
  if (K % 2 == 0) {
    cout << -1 << endl;
    return 0;
  }
  int64_t unit = log10(K) + 1;
  int sevens = stoi(string(unit, '7'));
  while (true) {
    sevens %= K;
    if (sevens % K == 0) {
      break;
    }
    sevens = sevens * 10 + 7;
    ++unit;
    
    if (unit > 10000000) {
      cout << -1 << endl;
      return 0;
    }
  }
  cout << unit << endl;

  return 0;
}


Measured memory_bytes: 3908
<?php
$h = STDIN;
$max = (int)fgets($h);
$a = explode(' ', fgets($h));

//10
//3 1 4 1 5 9 2 6 5 3

//6
//6 5 4 3 2 1

$i = 0;
$break = 0;
$ans = $max;
foreach ($a as $item) {
    $num = (int)$item;
    if ($num === $i + 1) {
        ++$i;
        continue;
    }
    ++$break;
}


if ($i === 0) {
    echo -1;
}else{
    echo $break;
}



Measured memory_bytes: 18936
#include <bits/stdc++.h>
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for (int i = (a); i < (b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define ALL(x) x.begin(), x.end()
#define chmax(x, y) x = max(x, y)
#define chmin(x, y) x = min(x, y)
using namespace std;
random_device rnd;
mt19937 mt(rnd());
using ll = long long;
using lld = long double;
using VI = vector<int>;
using VVI = vector<VI>;
using VL = vector<ll>;
using VVL = vector<VL>;
using PII = pair<int, int>;
const int IINF = 1 << 30;
const ll INF = 1ll << 60;
const ll MOD = 1000000007;
int n = 10;
VI dijkstra(VVI &dist, int start)
{
    VI ret(n, IINF);
    deque<PII> que;
    que.push_back({0, start});
    while (!que.empty())
    {
        int cost = que.front().first;
        int cur = que.front().second;
        que.pop_front();
        if (cost < ret[cur])
        {
            ret[cur] = cost;
            rep(i, 10)
            {
                que.push_back({cost + dist[i][cur], i});
            }
        }
    }
    return ret;
}

int main()
{
    int h, w;
    cin >> h >> w;
    VVI dist(10, VI(10));
    rep(i, 10) rep(j, 10) cin >> dist[i][j];
    auto cost = dijkstra(dist, 1);
    ll ans = 0;
    rep(i, h) rep(j, w)
    {
        int t;
        cin >> t;
        if (t != -1)
            ans += cost[t];
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 384
/* 
 * Author: pawanmsr
 */

#include <bits/stdc++.h>

using namespace std;
typedef long long int ll;

// Macro //
#define X first
#define Y second
#define pii pair<int,int>
#define pll pair<ll,ll>

// Global //
ll k;
ll gcds[202][202];

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

// Main //
int main(int argc, char const *argv[])
{
    // ios_base::sync_with_stdio(false);
    // cin.tie(NULL);
    
    /* code */
    cin >> k;
    // for (ll i=1; i<=k; i++) {
    //     for (ll j=1; j<=k; j++) {
    //         gcds[i][j] = gcd(i, j);
    //     }
    // }

    ll sm = 0;
    for (ll u=1; u<=k; u++) {
        for (ll v=1; v<=k; v++) {
            for (ll w=1; w<=k; w++) {
                sm += gcd(u, gcd(v,w));
            }
        }
    }

    cout << sm << endl;
    return 0;
}


Measured memory_bytes: 3628
def resolve():
    n = int(input())
    s = input()
    # 1 == sheep, 0 == wolf
    def next(before, now, answer):
        if now == True and answer == "o":
            return before
        elif now == True and answer == "x":
            return not before
        elif now == False and answer == "o":
            return not before
        elif now == False and answer == "x":
            return before
    for i in range(2**2):
        mena = [0]*n
        for j in range(2):
            mena[j] = (i >> j) & 1
        for j in range(1, n-1):
            mena[j+1] = next(mena[j-1], mena[j], s[j])
        if (next(mena[n-2], mena[n-1], s[n-1]) == mena[0]) and (next(mena[n-1], mena[0], s[0]) == mena[1]):
            OK = True
        else:
            OK = False
        if OK:
            ans = []
            for k in range(len(mena)):
                if mena[k]:
                    ans.append("S")
                else:
                    ans.append("W")
            print("".join(ans))
            exit()
    print(-1)
resolve()

Measured memory_bytes: 5364
#!/usr/bin/env python3
import sys


def solve(N: int, K: int, R: int, S: int, P: int, T: str):
    # 案①
    # 1. 勝ちパターンに変換し点数を計算 2 * O(N)
    # 2. K番目以降を確認し点数の差分を計算 O(N)?
    # →手を修正すると、修正後の手に応じてその先の手も修正が必要になるのでこの方法は無理。
    #
    # 案②
    # 修正後の手も考慮しつつ探索すれば良さそう。
    # あいこと負けどちらを選ぶかは、K手先を見て決める
    # 計算量は大体 O((N/K) * K) = O(N)

    m = {'r': 'p', 's': 'r', 'p': 's'}
    nt = list(''.join([m[i] for i in T]))
    pm = {'r': R, 's': S, 'p': P}
    flgs = [0] * N
    ans = 0
    for i in range(N):
        if flgs[i]:
            continue
        piece = nt[i::K]
        for j, jv in enumerate(piece):
            if j - 1 >= 0 and jv == piece[j - 1]:
                jv = piece[j] = m[jv]
                if j + 1 < len(piece) and jv == piece[j + 1]:
                    jv = piece[j] = m[jv]
            else:
                ans += pm[jv]
            idx = i + (j * K)
            nt[idx] = jv
            flgs[idx] = 1
    print(ans)
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    R = int(next(tokens))  # type: int
    S = int(next(tokens))  # type: int
    P = int(next(tokens))  # type: int
    T = next(tokens)  # type: str
    solve(N, K, R, S, P, T)

if __name__ == '__main__':
    main()


Measured memory_bytes: 5740
//       In the name of         ****                      God                     ****

/*

Copyright (C)          JadedBeast

                                   Morocco

created : 10/3/2019

*/

#include <bits/stdc++.h>
using namespace std;
#define time cout << "\ntime: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
#define W 100001
inline void Boost() {
	cin.tie(0);cin.sync_with_stdio(0);
	cout.tie(0);cout.sync_with_stdio(0);
}
long long n,w,DP[101][W],knap[101][2];
long long dp(int i,int weight){
	if(weight==0 || i>=n)
		return 0;
	if(weight <0 )
		return -69696969;
	if(DP[i][weight]!=-1)
		return DP[i][weight];
	if(weight>=knap[i][0])
		return DP[i][weight]=max(knap[i][1]+dp(i+1,weight-knap[i][0]),dp(i+1,weight));
	else
		return DP[i][weight]=dp(i+1,weight);
}



int main(void){
	Boost();
	cin >>n >> w;
	for(int i=0 ; i<n ;i++)
		for(int j=0; j<2;j++)
			cin >>knap[i][j];

	memset(DP,-1,sizeof(DP));

	cout << dp(0,w)<<endl;
   return 0;
}


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

using namespace std;

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

    if(n%1000 > 0)
    {
        cout << ((n/1000) +1) * 1000 - n;
    }
    else
    {
        cout << 0 << endl;
    }
    return 0;
}


Measured memory_bytes: 3640
#include <bits/stdc++.h>
#include <vector>
#include <cstdlib>
using namespace std;
int main(void){
  int A, B, C;
  cin >> A >> B >> C;
  if(A == B){
    cout << C;
  } else if(A == C){
    cout << B;
  } else {
    cout << A;
  }
}

Measured memory_bytes: 256
from fractions import gcd
# from datetime import date, timedelta
from heapq import*
import math
from collections import defaultdict, Counter, deque
from bisect import *
import itertools
import fractions
import sys
sys.setrecursionlimit(10 ** 7)
MOD = 10 ** 9 + 7
# input = sys.stdin.readline

def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i)

    divisors.sort()
    return divisors

def main():
    s, t = input().split()
    print(t+s)
    
            
                

        




    


if __name__ == '__main__':
    main()


Measured memory_bytes: 66028
#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<stack>
#include<queue>
#include<string>
#include<set>
#include<map>
using namespace std;
#define rep(i,n) for(int i=0;(i)<(n);(i)++)
#define FOR(i,m,n) for(int i=(m);(i)<(n);(i)++)
typedef long long ll;

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

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

int main(){
    int n; cin >> n;
    vector<ll> clk(n);
    rep(i,n){
        cin >> clk[i];
    }
    ll res = clk[0];
    for(int i=1;i<n;i++){
        res = lcm(res,clk[i]);
    }

    cout << res << endl;
    return 0;
}

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

#define rep2(x,fr,to) for(int (x)=(fr);(x)<(to);(x)++)
#define rep(x,to) for(int (x)=0;(x)<(to);(x)++)
#define repr(x,fr,to) for(int (x)=(fr);(x)>=(to);(x)--)
#define all(c) (c).begin(),(c).end()
#define sz(v) (int)(v).size()

using namespace std;
typedef long long ll; typedef vector<int> VI; typedef pair<int,int> pii;
const int MD = (int)1e9 + 7; typedef vector<ll> VL;
void dbg(){ cerr << "\n"; }  template <class T, class ...T2>
void dbg(const T& fst, const T2&...rst){ cerr << fst << ": "; dbg(rst...); }


int main() {
	cin.tie(0); ios_base::sync_with_stdio(false);
	int n, m;
	cin >>n  >>m;
	
	vector<VI> r(n);
	VI cnd(n);
	vector<vector<bool>> aru(n, vector<bool>(n));
	rep(i, m){
		int a,b; cin >>a >>b; a--;b--;
		r[a].push_back(b);
		aru[a][b] = true;
		cnd[a] |=1; cnd[b] |=2;
	}
	auto bfs =[&](int s) -> tuple<int, int, VI>{
		
		VI dd(n, MD), vp(n ,-1);
		queue< int > que;
		que.push(s); dd[s] = 0; vp[s] = -2;
		while(!que.empty()){
			int cr = que.front();
			que.pop();
			for(auto x: r[cr]){
				if(vp[x] ==-1){
					que.push(x);
					dd[x] = dd[cr]+1;
					vp[x] = cr;
				}
			}
		}
		
		int mn = MD, svj=-1;
		rep(j, n) if(j!=s && dd[j] < MD && aru[j][s]){
			if(mn > dd[j]){
				mn = dd[j]; svj =j;
			}
		}
		
		return make_tuple(mn, svj, vp);
	};
	
	int mn = MD;
	tuple<int, int, VI>  bst =make_tuple(MD, -1, VI{});
	rep(i, n){
		if((cnd[i]&3) !=3) continue;
		auto rv = bfs(i);
		if(get<0>(bst) > get<0>(rv)) bst = rv;
	}
	if(get<1>(bst) == -1) puts("-1");
	else{
		VI ans;
		int p = get<1>(bst);
		while(p >=0){
			ans.push_back(p);
			p = get<2>(bst)[p];
		}
		reverse(all(ans));
		cout << sz(ans) <<"\n";
		for(auto z: ans) cout << z+1 <<"\n";
	}
	return 0;
	
}


Measured memory_bytes: 512
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Main main = new Main();
        main.solve();
    }
    public void solve() {
        Scanner scan = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        int H = scan.nextInt();
        int N = scan.nextInt();
        List<Pair> list = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            Pair p = new Pair(scan.nextInt(), scan.nextInt());
            list.add(p);
        }
        //list.sort(new PairComparator());
        long[] dp = new long[30000+1];
        Arrays.fill(dp, Long.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < H; i++) {
            if (dp[i] == Long.MAX_VALUE) {
                continue;
            }
            for (int j = 0; j < N; j++) {
                Pair p = list.get(j);
                dp[i + p.A] = Math.min(dp[i + p.A], dp[i]+p.B);
            }
        }
        long answer = Long.MAX_VALUE;
        for (int i = H; i <= 30000; i++) {
            answer = Math.min(answer, dp[i]);
        }
        System.out.println(answer);
    }
    class Pair {
        int A;
        int B;
        Pair(int A, int B) {
            this.A = A;
            this.B = B;
        }
    }
    class PairComparator implements Comparator<Pair> {
        @Override
        public int compare(Pair o1, Pair o2) {
            if (o1.A != o2.A) {
                return Integer.compare(o1.A, o2.A);
            }
            return Integer.compare(o1.B, o2.B);
        }
    }
}


Measured memory_bytes: 26572
/**
 * author:    Ziel
 * created:   20.04.2020 15:33:24
**/

// ~zaletaet~

//#pragma GCC optimize("Ofast")
//#pragma GCC target("avx,avx2,fma")
#include <bits/stdc++.h>

#define fi first
#define se second
#define sz(x) int(x.size())
#define all(x) x.begin(), x.end()
#define pb push_back

using namespace std;

using ll = long long;
using ull = unsigned long long;
// using big = __int128_t; // -10^38...10^38
typedef pair<int,int> ii;
typedef pair<ll,ll> pll;

const ll N = 1e5 + 123, MOD = 1e9 + 7, oo = 1e9 + 9, INF = 1e18 + 9;
const double EPS = 1e-9, PI = acos(-1); // 3.14159265358979323846
const int dx[] = {1, -1, 0, 0, 1, 1, -1, -1}, dy[] = {0, 0, 1, -1, 1, -1, -1, 1};

ostream& operator<<(ostream& os, const multiset<ll>& a) {
	os << "( ";
	bool isfirst = true;
	for (auto i: a) {
		if (isfirst) {
			os << i;
			isfirst = false;
		} else {
			os << ", " << i;
		}
	}
	os << " )";
	return os;
}

ostream& operator<<(ostream& os, const multiset<ll, greater<ll>>& a) {
	os << "( ";
	bool isfirst = true;
	for (auto i: a) {
		if (isfirst) {
			os << i;
			isfirst = false;
		} else {
			os << ", " << i;
		}
	}
	os << " )";
	return os;
}

main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
	
	int n;
	cin >> n;
	
	vector<int> a(3 * n);
	for (int& i: a) cin >> i;
	
	ll sum1 = 0, sum2 = 0;
	multiset<ll, greater<ll>> m1;
	multiset<ll> m2, m3;
	for (int i = 0; i < n; i++) {
		m1.insert(a[i]);
		sum1 += a[i];
	}
	for (int i = n; i < n + n + n; i++) {
		m2.insert(a[i]);
	}
	while (sz(m2) > n) {
		auto iter = m2.end();
		iter--;
		m3.insert(*iter);
		m2.erase(iter);
	}
	int it = 0;
	for (auto i: m2) {
		if (it >= n) break;
		sum2 += i;
		it++;
	}
	
	ll ans = sum1 - sum2;
//	cout << m1 << ' ' << sum1 << '\n' << m2 << ' ' << sum2 << '\n' << m3 << '\n' << '\n';
	for (int i = n; i < n + n; i++) {
		if (*m1.rbegin() < a[i]) {
			auto iter = m1.end();
			iter--;
			sum1 -= *iter;
			m1.erase(iter);
			sum1 += a[i];
			m1.insert(a[i]);
		}
		if (a[i] <= *m2.rbegin()) {
			sum2 -= a[i];
			auto iter = m2.lower_bound(a[i]);
			m2.erase(iter);
			sum2 += *m3.begin();
			m2.insert(*m3.begin());
			m3.erase(m3.begin());
		} else {
			auto iter = m3.lower_bound(a[i]);
			m3.erase(iter);
		}
		ans = max(ans, sum1 - sum2);
//		cout << m1 << ' ' << sum1 << '\n' << m2 << ' ' << sum2 << '\n' << m3 << '\n' << '\n';
	}
	
	cout << ans;
	return 0;
}



Measured memory_bytes: 15488
#include <bits/stdc++.h>
using namespace std;
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define REP(i,n) for(ll i=0;i<n;i++)
#define FOR(i,n1,n2) for(ll i=n1;i<n2;i++)
#define bFOR(i,n1,n2) for(ll i=n1;i>=n2;i--)
#define speed_up    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
typedef long long int ll;
typedef pair<ll,ll> Pi;
typedef tuple<ll,ll,ll> Tu;
const int INF=(ll)(1LL<<30)-1;
const double INFd=100000000000.0;
const double PI=3.14151926535;
const ll INFl=(ll)9223372036854775807;
const int MAX=10000;
const ll MOD=(ll)1e9+7;
const ll tMOD=(ll)998244353;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a, b)*b;}
int dx[4]={0,-1,0,1},dy[4]={-1,0,1,0};
int mdx[8]={0,1,0,-1,1,1,-1,-1},mdy[8]={-1,0,1,0,1,-1,1,-1};


template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){
    std::fill( (T*)array, (T*)(array+N), val );
}

int n;
int d[100100]={};
int main(){
    cin>>n;
    REP(i,n){
        int a,b;
        cin>>a>>b;
        d[a]++;
        d[b+1]--;
    }
    FOR(i,1,100100){
        d[i]+=d[i-1];
    }
    int ans=0;
    FOR(i,1,100100){
        if(d[i]+1>=i)ans=i;
    }
    cout<<ans-1<<endl;
    return 0;
}


Measured memory_bytes: 3484
/*	ex9_2
	suzuto	*/

#include <stdio.h>
#include <stdlib.h>

#define  SIZE 100000

typedef struct cube{ /*積まれたキューブを下から順に参照するための構造体を作る*/
  char color;
  struct cube *next;
}cube;

/*プロトタイプ宣言*/
cube *insert_cube(cube *cube_bottom, char add_elem);
cube *delete_cube(cube *cube_ptr, cube *prev_ptr, cube *cube_bottom);

int main(void) {
  cube *lower_stack, *upper_stack; /*変数の宣言*/
  char inp[SIZE + 1], ins;
  int i, count = 0;

  lower_stack = NULL; /*リストの初期化*/
  scanf("%s", inp); /*文字列を入力*/

  for(i = 0; i < SIZE + 1; i++){ /*入力をリストに追加していく*/
    ins = inp[i];
    if(ins == '\0'){ /*末尾の識別*/
      break;
    }
    lower_stack = insert_cube(lower_stack, ins); /*リストを拡張*/
  }

  upper_stack = NULL; /*参照位置より上のキューブを記憶するためのリストを初期化*/
  while(lower_stack != NULL){ /*参照位置の上下で色が一致するかを調べる*/
    if(upper_stack == NULL){ /*上に何もなければ参照位置を一つ下げるだけ*/
      upper_stack = insert_cube(upper_stack, lower_stack->color);
      lower_stack = delete_cube(lower_stack, NULL, lower_stack);
    }else if(upper_stack->color != lower_stack->color){ /*色が不一致の時はそれらを削除*/
      upper_stack = delete_cube(upper_stack, NULL, upper_stack); /*参照位置の上を削除*/
      lower_stack = delete_cube(lower_stack, NULL, lower_stack); /*参照位置の下を削除*/
      count += 2; /*カウントを更新*/
    }else{ /*色が一致している時は参照位置を下げる*/
      upper_stack = insert_cube(upper_stack, lower_stack->color);
      lower_stack = delete_cube(lower_stack, NULL, lower_stack);
    }
  }
  printf("%d\n", count); /*結果を出力*/
  return 0;
}

cube *insert_cube(cube *cube_bottom, char add_elem){ /*リストの先頭に要素を追加する関数*/
  cube *new; /*変数の宣言*/

  if((new = calloc(1, sizeof(cube))) == NULL){ /*配列の領域が確保を確保できなかった時のエラー出力*/
    fprintf(stderr, "Calloc error.\n");
  }
  new->color = add_elem; /*新しく確保した領域に要素を格納*/
  new->next = cube_bottom; /*先頭を更新*/
  return new;
}

cube *delete_cube(cube *cube_ptr, cube *prev_ptr, cube *cube_bottom){ /*リスト内の指定した位置の要素を削除する関数*/
  cube *res_bottom; /*変数の宣言*/

  if(prev_ptr == NULL){ /*消す位置が先頭の時*/
    res_bottom = cube_ptr->next; /*リストの先頭を変更*/
    free(cube_ptr); /*削除した位置を解放*/
    return res_bottom;
  }
  prev_ptr->next = cube_ptr->next; /*リストを接続し直す*/
  free(cube_ptr); /*削除した位置を解放*/
  return cube_bottom;
}


Measured memory_bytes: 4924
#include <bits/stdc++.h>
using namespace std;
int main(void){
    int l, r, d;
    cin >> l >> r >> d;
    
    int cnt = 0;
    for(int i = l;i <= r;i++){
        if(i % d == 0){
            cnt++;
        }
    }
    
    cout << cnt;
    
    return 0;
}


Measured memory_bytes: 3564
#include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#include "dump.hpp"
#else
#define dump(...)
#endif

//#define int long long
#define rep(i, a, b) for (int i = (a); i < (b); i++)
#define rrep(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define all(c) begin(c), end(c)
const int INF =
    sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = 1e9 + 7;
template <class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}

signed main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int A, B, C;
    cin >> A >> B >> C;
    cout << min(C, B / A) << endl;
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repe(i, n) for (int i = 0; i <= (int)(n); i++)
#define YES cout<<"YES"<<endl
#define NO cout<<"NO"<<endl
#define Yes cout<<"Yes"<<endl
#define No cout<<"No"<<endl
#define ANS cout << ans << endl
#define all(a) a.begin(),a.end()
#define SORT(a) sort(all(a))
#define REVERSE(a) reverse(all(a))
#define KOZYUN(a) sort(all(a),greater<int>())
#define int ll
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define FORe(i, m, n) for(int i = m;i <= n;i++)
#define VIin(a) for(int i=0; i<a.size(); i++) cin >> a[i]
#define OUT(a) cout << a << endl
#define IN(a) cin >> a
#define INT(a) int a; cin >> a
typedef vector<int> VI;
typedef vector<VI> VVI;
const int MOD=1e9+7;
const long long INF = 1LL << 60;
/*最大公約数*/int gcd(int x, int y) { return y ? gcd(y,x%y) : x;}
/*最小公倍数*/int lcm(int a, int b) { int g = gcd(a, b); return a / g * b; }
/*素数判定*/int isPrime(int n){if(n<2){return 0;}for(int i=2; i*i<=n; i++){if(n%i==0){return 0;}}return 1;}
/*約数列挙*/vector<int> getDivisor(int n){vector<int> v; for(int i=1; i*i<=n; i++){if(n%i==0){v.push_back(i);if(i!=n/i){v.push_back(n/i);}}}sort(v.begin(),v.end()); return v;}
//----------------------------------------------
signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    INT(n);INT(k);
    VI cnt(n+1);
    rep(i,n){
        INT(x);
        cnt[x]++;
    }
    KOZYUN(cnt);
    int ans = 0;
    rep(i,k) ans += cnt[i];
    OUT(n-ans);

    return 0;
}

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

using namespace std;

#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define BW(a,x,b) ((a)<=(x)&&(x)<=(b))
#define ALL(v) (v).begin(), (v).end()
#define LENGTHOF(x) (sizeof(x) / sizeof(*(x)))
#define AFILL(a, b) fill((int*)a, (int*)(a + LENGTHOF(a)), b)
#define MP make_pair
#define PB push_back
#define F first
#define S second
#define INF 1 << 30
#define EPS 1e-10

typedef pair<int, int> pi;
typedef pair<int, pi> pii;
typedef vector<int> vi;
typedef queue<int> qi;
typedef long long ll;

int dp0[16][2048], N, K, dp[16][2048];
// vector<pi>b;
vector<vector<int> >b(10);

bool cmp(const pi &a, const pi &b){
  if(a.S != b.S) return a.S < b.S;
  return a.F > b.F;
}

int main(){
  scanf("%d%d", &N, &K);
  int C, G;
  rep(i, N){
    scanf("%d%d", &C, &G); G--;
    b[G].PB(C);
  }

  rep(i, 10){
    sort(b[i].begin(), b[i].end(), greater<int>());
    rep(j, b[i].size()) dp0[i][j+1] = dp0[i][j] + b[i][j] + 2*j;
  }

  rep(i, 10){
    rep(j, b[i].size()+1){
      for(int k = 0; k + j <= K; k++){
	dp[i+1][k+j]=j?max(dp[i][k]+dp0[i][j],dp[i+1][k+j]):dp[i][k+j];
      }
    }
  }
  /*  rep(i, 11){
    rep(j, 7) printf("%d ", dp[i][j]); puts("");
    }*/

  printf("%d\n", dp[10][K]);
  return 0;
}

Measured memory_bytes: 1352
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
#define rep(i,n) for(int i = 0; i < ((int)(n)); i++)   // 0-indexed昇順

int main() {
    string s, t;
    cin >> s >> t;
    sort(s.begin(), s.end());
    sort(t.begin(), t.end(), greater<char>());
    if (s < t) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}


Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define MOD (1000000007l)
#define ll long long
#define rep(i, n) for (ll i = 0; i < (n); i++)

using namespace std;

char cake[310][310];
ll ans[310][310];

void solve() {
  rep (h, 310) rep (w, 310) {
    cake[h][w] = 0;
    ans[h][w] = 0;
  }
  ll H, W, K;
  cin >> H >> W >> K;
  rep (h, H) cin >> cake[h];
  ll count = 1;
  rep (h, H) rep (w, W) {
    if (cake[h][w] == '#') {
      ans[h][w] = count;
      count++;
    }
  }
  for (ll h = 0; h < H; h++) for (ll w = 1; w < W; w++) {
    if (ans[h][w] == 0) ans[h][w] = ans[h][w-1];
  }
  for (ll h = 0; h < H; h++) for (ll w = W-2; w >= 0; w--) {
    if (ans[h][w] == 0) ans[h][w] = ans[h][w+1];
  }
  for (ll w = 0; w  < W; w++) for (ll h = 1; h < H; h++) {
    if (ans[h][w] == 0) ans[h][w] = ans[h-1][w];
  }
  for (ll w = 0; w  < W; w++) for (ll h = H-2; h >= 0; h--) {
    if (ans[h][w] == 0) ans[h][w] = ans[h+1][w];
  }
  rep (h, H) {
    bool flag = false;
    rep (w, W) {
      if (flag) cout << " ";
      flag = true;
      cout << ans[h][w];
    }
    cout << endl;
  }
}

int main(void) {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout.precision(12);
  solve();
  return 0;
}


Measured memory_bytes: 1664
N,K=input().split()
D=input().split()
E=[int(n) for n in D]

while True:
    numbers=[]
    for a in N:
        b=int(a)
        numbers.append(b)
    for c in numbers:
        if c in E:
            z = int(N)
            z += 1
            N = str(z)
            break

    else:
        print(N)
        break

Measured memory_bytes: 3064
from collections import Counter
N = int(input())
def prime_factors(n):
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return factors
num = Counter()
for n in range(1, N + 1):
    factors = prime_factors(n)
    num.update(factors)
x = 1
for _, n in num.items():
    x *= (n + 1)
    x %= 10 ** 9 + 7
print(x)


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

typedef long long ll;
typedef pair<int, int> ii;

const int MOD = 1e9 + 7;
int n;
ll a, b, res;
unordered_map<string, ii> ma;

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

ll power(ll a, ll b) {
  ll res = 1;
  while (b) {
    if (b & 1) {
      res = (res * a) % MOD;
    }
    a = a * a % MOD;
    b >>= 1;
  }
  return res;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  ll z = 0;
  ll az = 0; // a = 0, b != 0
  ll bz = 0; // a != 0, b = 0
  for (int i = 0; i < n; ++i) {
    cin >> a >> b;
    if (!a && !b) {
      ++z;
      continue;
    } else if (a == 0) {
      ++az;
      continue;
    } else if (b == 0) {
      ++bz;
      continue;
    }
    // a != 0, b != 0
    bool neg = (a < 0) ^ (b < 0);
    a = abs(a);
    b = abs(b);
    ll c = gcd(a, b);
    a /= c;
    b /= c;
    if (neg) {
      string k = to_string(b) + ',' + to_string(a);
      ++ma[k].first;
    } else {
      string k = to_string(a) + ',' + to_string(b);
      ++ma[k].second;
    }
  }
  res = (power(2, az) + power(2, bz) - 1) % MOD;
  for (auto p : ma) {
    ll c1 = p.second.first, c2 = p.second.second;
    res = ((power(2, c1) + power(2, c2) - 1) % MOD * res) % MOD;
  }
  res = (res + z - 1) % MOD;
  if (res < 0) res += MOD;
  cout << res << endl;
  
  return 0;
}


Measured memory_bytes: 27132
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ITP1_7_C
{
    public class Program

    {
        public static void Main(string[] args)
        {
            int[] line = ReadIntAr();
            int[,] rlt = new int[line[0]+1, line[1]+1];

            for (int i = 0 ; i < line[0] ; i++)
            {
                int[] tmp = ReadIntAr();

                for (int j = 0 ; j < line[1] ; j++)
                {
                    rlt[i, j] = tmp[j];
                    rlt[i, line[1]] += tmp[j];
                    rlt[line[0], j] += tmp[j];
                    rlt[line[0], line[1]] += tmp[j];
                }
            }

            for (int i = 0 ; i <= line[0] ; i++)
            {

                for (int j = 0 ; j <= line[1] ; j++)
                {
                    Console.Write(rlt[i,j]);
                    if (j == line[1]) Console.Write(Environment.NewLine);
                    else Console.Write(" ");
                }
            }            
        }

        static string ReadSt() { return Console.ReadLine(); }
        static int ReadInt() { return int.Parse(Console.ReadLine()); }
        static long ReadLong() { return long.Parse(Console.ReadLine()); }
        static double ReadDouble() { return double.Parse(Console.ReadLine()); }
        static string[] ReadStAr(char sep = ' ') { return Console.ReadLine().Split(sep); }
        static int[] ReadIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => int.Parse(e)); }
        static long[] ReadLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => long.Parse(e)); }
        static double[] ReadDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Split(sep), e => double.Parse(e)); }

    }

}



Measured memory_bytes: 18004
#include<cstdio>
#include<cstring>

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

int map[1000][1000];

void dfs(int x, int y, int d, int &res) {
    if(d>t+1) return;
    if(map[x][y] && map[x][y] <= d) return;
    if(!map[x][y]) res++;
    map[x][y] = d;

    for(int dir=0; dir<6; dir++)
        dfs(x+dx[dir], y+dy[dir], d+1, res);
}

int main(void) {
    while(1) {
        int n;
        scanf("%d%d",&t,&n);
        if(!t) break;

        memset(map, 0, sizeof(map));

        for(int i=0; i<n; i++) {
            int x,y;
            scanf("%d%d",&x,&y);
            x+=300; y+=300;
            map[x][y] = -1;
        }
        int x,y,res=0;
        scanf("%d%d",&x,&y);
        dfs(x+300,y+300,1,res);

        printf("%d\n",res);
    }
    return 0;
}

Measured memory_bytes: 4940
N = int(input())

DP = [100010]*(N+1)
DP[0] = 0

for i in range(1, N+1):
    tmp_s = 1
    tmp_n = 1
    while tmp_s <= i:
        DP[i] = min(DP[i], DP[i-tmp_s]+1)
        tmp_s *= 6
    while tmp_n <= i:
        DP[i] = min(DP[i], DP[i-tmp_n]+1)
        tmp_n *= 9
    
    DP[i] = min(DP[i], DP[i-1]+1)

print(DP[-1])

Measured memory_bytes: 3828
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define pb push_back
#define mk make_pair
#define f first
#define s second
#define vs (v.begin(),v.end())
#define MOD 1000000007

int main()
{  
  
  ll n;
  cin>>n;
  ld x[n+1]={0.0};
  for(ll i=1;i<=n;i++)
    cin>>x[i];
  ld dp[n+1][n+1];
  for(ll i=0;i<=n;i++)
    for(ll j=0;j<=n;j++)
      dp[i][j]=0.0;
     dp[0][0]=1.0;
  for(ll i=1;i<=n;i++)
  {
    for(ll j=0;j<=n;j++)
    { 
      if(j==0)
      {
         dp[i][j]=(ld)dp[i-1][j]*(ld)(1-x[i]);
      }
      else
      dp[i][j]=(ld)dp[i-1][j]*(ld)(1-x[i])+(ld)dp[i-1][j-1]*(ld)x[i];
    }
  }
  ld ans=0.0;
  for(ll j=(n+1)/2;j<=n;j++)
    ans+=dp[n][j];
  cout<<setprecision(10)<<ans<<endl;
  

  



}
    
   

         




  
   


  
              
              

  

  
  
          
      
    







  
 

Measured memory_bytes: 140928
N,M=map(int,input().split())
A=[[]for i in range(N)]
for i in range(M):
  a,b=map(int,input().split())
  A[a-1].append(b-1)
S,T=map(int,input().split())  
from collections import deque
import sys
sys.setrecursionlimit(10**7) #再帰制限のとっぱらい
D=[[-1]*3 for i in range(N)]
def bfs(x,n):
  q=deque()
  q.append((x,n)) 
  while len(q):
    x,n=q.popleft()
    for i in A[x]:
      d=(n+1)%3
      if D[i][d]==-1:
        D[i][d]=D[x][n]+1
        q.append((i,d))
D[S-1][0]=0
bfs(S-1,0)
if D[T-1][0]==-1:
  print(-1)
else:
  print(D[T-1][0]//3)

Measured memory_bytes: 100924
#include <bits/stdc++.h>
#define REP(i, n) for (ll i = 0; i < (n); i++)
#define INF 1e9
#define MOD 1000000007
#define All(x) (x).begin(), (x).end()
typedef long long ll;
using namespace std;

ll dp[1100][5000];

int main(void){
    int N,M;cin>>N>>M;
    vector<ll> a(M),b(M),c(M,0);
    for(int i=0;i<M;i++){
        cin>>a[i]>>b[i];
        for(int j=0;j<b[i];j++){
            int t;cin>>t;t--;
            c[i]+=(1<<t);
        }
    }

    for(int i=0;i<1100;i++){
        for(int j=0;j<5000;j++){
            dp[i][j]=INF;
        }
    }
    dp[0][0]=0;

    for(int i=0;i<M;i++){
        for(int j=0;j<(1<<N);j++){
            dp[i+1][j]=min(dp[i+1][j],dp[i][j]);

            int nj=j|c[i];
            dp[i+1][j|c[i]]=min(dp[i+1][j|c[i]],dp[i][j]+a[i]);
        }
    }

    cout<<(dp[M][(1<<N)-1]<INF ? dp[M][(1<<N)-1] : -1)<<endl;
}

Measured memory_bytes: 43264
#pragma once
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <utility>
#include <set>
#include <cctype>
#include <queue>
#include <stack>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <deque>
#include <numeric>
#include <iomanip>
#define M_PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int INF = 1000000007;
const int MAX_V = 201;
int now = 0;

const int MAX = 510000;
const int MOD = 1000000007;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
	fac[0] = fac[1] = 1;
	finv[0] = finv[1] = 1;
	inv[1] = 1;
	for (int i = 2; i < MAX; i++) {
		fac[i] = fac[i - 1] * i % MOD;
		inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
		finv[i] = finv[i - 1] * inv[i] % MOD;
	}
}

// 二項係数計算
long long COM(int n, int k) {
	if (n < k) return 0;
	if (n < 0 || k < 0) return 0;
	return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}
struct edge {
	int t;
	edge(int _t) : t(_t) {}
};
bool use[100010];


vector<edge> te[100010];
vector<edge> fe[100010];
int d[100100];
//ll rec(int num) {
//	if (num == 0) return 0;
//	return rec(num - 1) + num;
//}
ll gcd(int a, int b) {
	if (b == 0) return a;
	return gcd(b, a % b);
}

ll calc(ll b,ll n){
	if (n < b) return n;
	return calc(b, n / b) + n % b;
}

void Solve() {

	int a, b,q;
	cin >> a >> b >> q;
	ll s[100010],t[100010];
	for (size_t i = 0; i < a; i++)
	{
		cin >> s[i];
	}
	for (size_t i = 0; i < b; i++)
	{
		cin >> t[i];
	}
	for (size_t i = 0; i < q; i++)
	{
		ll q;
		cin >> q;
		ll *slp = lower_bound(s, s + a, q);
		ll sl = *lower_bound(s, s + a, q);
		if (s < slp && sl > q) {
			sl =*--slp;
		}

		ll su = *upper_bound(s, s + a, q);

		if (q > s[a - 1]) {
			sl = s[a - 1];
			su = s[a - 1];
		}

		ll *tlp = lower_bound(t, t + b, q);
		ll tl = *lower_bound(t, t + b, q);
		if (t < tlp&& tl > q) {
			tl = *--tlp;
		}
		ll tu = *upper_bound(t, t + b, q);
		if (q > t[b - 1]) {
			tl = t[b - 1];
			tu = t[b - 1];
		}


		ll sum =       abs(sl - q) + min(abs(sl - tl), abs(sl - tu));
		sum = min(sum, abs(su - q) + min(abs(su - tl), abs(su - tu)));
		sum = min(sum, abs(tl - q) + min(abs(tl - sl), abs(tl - su)));
		sum = min(sum, abs(tu - q) + min(abs(tu - sl), abs(tu - su)));
		cout << sum << endl;
	}
}


int main() {
	Solve();
	return 0;
}



Measured memory_bytes: 8576
#include<stdio.h>
#include<stdlib.h>

int main(void) {
	char s[100000] = {'0'};
  scanf("%s", s);
	int i;
	for(i=0; s[i] != '\0'; i++) {
		if(i % 2 == 0){
			printf("%c", s[i]);
		}
	}
	printf("\n");
	return 0;
}

Measured memory_bytes: 256
class BIT(object):
    def __init__(self, size):
        self.size = size
        self.bit = [0] * (self.size + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.bit[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.bit[i] += x
            i += i & -i

    def __str__(self):
        return str(self.bit)

n, m = map(int,input().split())
lr = [[] for i in range(m + 1)]
for i in range(n):
    l, r = map(int,input().split())
    lr[r - l + 1].append(l)

bit = BIT(m + 1)
t = 0
for d in range(1, m + 1):
    for l in lr[d]:
        #print(l, l + d)
        bit.add(l, 1)
        #print(bit.bit)
        bit.add(l + d, -1)
        #print(bit.bit)

    t += len(lr[d])
    ans = n - t

    cur = 0
    while cur <= m:
        # bitの0 ~ curまでの総和を加算
        ans += bit.sum(cur)
        cur += d

    print(ans)


Measured memory_bytes: 80800
n, k = map(int, input().split())
a = list(map(int, input().split()))
def f(x):
  ret = 0
  for i in range(n):
    ret += a[i]^x
  return ret

import math
if k == 0:
  print(f(0))
else:
  bit = int(math.log(k, 2))
  check= [0] * (bit + 1) 
  for i in range(bit + 1):
    check[i] = (sum([(a[j] & 2**i) // (2**i) for j in range(n)]))

  ans = [f(k)]
  for i in range(bit + 1):
    x = 0
    if k&(2**i) > 0:
      for j in range(bit + 1):
        if check[j] <= ((n-1) // 2) and j < i:
          x += 2**j
        if j > i:
          x += k&(2**j)
    ans.append(f(x))
  print(max(ans))

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

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

  int n;
  cin >> n;
  vector<int> l(2 * n);
  for (int i = 0; i < 2 * n; ++i) {
    cin >> l[i];
  }
  sort(l.begin(), l.end());
  int ans = 0;
  for (int i = 0; i < n; ++i) {
    ans += l[2 * i];
  }
  cout << ans << "\n";
}


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

#Takahashi eats a, k times while Aoki doesn't eat b unless
#all of a's are gone.

if a+b <= k: #all cookies will be gone
    print(0,0)
else:
    if a <= k:
        print(0, b-(k-a))
    else:
        print(a-k, b)

Measured memory_bytes: 2940
s = input()
q = int(input())

for i in range(q):
    order = list(map(str,input().split()))
    a,b = int(order[1]),int(order[2])
    if order[0] == 'replace':
        s = s[:a] + order[3] + s[b+1:]
    elif order[0] == 'reverse':
        s = s[:a] + s[a:b+1][::-1] + s[b+1:]
    else:
        print(s[a:b+1])


Measured memory_bytes: 5612
/*
    数据量很小,直接模拟
    对最大的数-n,其他数+1,直到最大数都小于n
    问操作次数.
    数据量大时,二分也应该可以.
*/
#include<cstdio>
using namespace std;
typedef long long LL;
LL a[55];
int main(){
    LL n, ans = 0;
    scanf("%lld", &n);
    for (int i = 0; i < n;i++){
        scanf("%lld", a + i);
    }
    while(true){
        LL ma = a[0], pos = 0;
        for (int i = 1; i < n;i++){
            if(a[i]>ma){
                ma = a[i];
                pos = i;
            }
        }
        if(ma<n){
            break;
        }
        LL tmp = ma / n;
        a[pos] %= n;
        for (int i = 0; i < n;i++){
            a[i] += tmp;
        }
        a[pos] -= tmp;
        ans += tmp;
    }
    printf("%lld", ans);
    return 0;
}

Measured memory_bytes: 128
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.math.*;

public class Main {
    private static Scanner sc;

    public static void main(final String[] args) {
        final Main instance = new Main();
        sc = instance.new Scanner();
        instance.solve();
    }

    private class Scanner {
        String[] s;
        int i;
        BufferedReader br;
        String regex = " ";

        public Scanner() {
            s = new String[0];
            i = 0;
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        @Override
        protected void finalize() throws Throwable {
            try {
                super.finalize();
            } finally {
                destruction();
            }
        }

        private void destruction() throws IOException {
            if (br != null)
                br.close();
        }

        public String next() throws IOException {
            if (i < s.length)
                return s[i++];
            String st = br.readLine();
            while (st == "")
                st = br.readLine();
            s = st.split(regex, 0);
            i = 0;
            return s[i++];
        }

        public int nextInt() throws NumberFormatException, IOException {
            return Integer.parseInt(next());
        }

        public Long nextLong() throws NumberFormatException, IOException {
            return Long.parseLong(next());
        }

        public Double nextDouble() throws NumberFormatException, IOException {
            return Double.parseDouble(next());
        }

        public long[] nextLongArray(int n) throws NumberFormatException, IOException {
            long[] ret = new long[n];
            for (int i = 0; i < n; i++) {
                ret[i] = nextLong();
            }
            return ret;
        }
    }

    private void solve() {
        try {
            //int n = sc.nextInt();
            long[] a= sc.nextLongArray(5);
            int i=0;
            for(i=0;i<5;i++){
                if(a[i]==0) break;

            }
            
            System.out.println(i+1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}


Measured memory_bytes: 32468
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MOD = 1000000007;

signed main() {
  
  int N, M;
  cin >> N >> M;
  
  int sum = 0;
  vector<int> A(N);
  for( int i = 0; i < N; i++ ){
    cin  >> A.at(i);
    sum += A.at(i);
  }
  
  int ans = 0;
  for( int i = 0; i < N; i++ ){
    if( A.at(i) >= sum/(4*M) ){
      int B = sum/(4*M);
      if( sum%(4*M) == 0 ) ans++;
      else if( A.at(i) == B ) continue;
      else ans++;
    }
  }
  if( ans >= M ) cout << "Yes" << endl;
  else cout << "No" << endl;

}

Measured memory_bytes: 256
# ABC075 B-Minesweeper
import numpy as np

H, W = map(int, input().split())
s = np.zeros((H+2, W+2))

for i in range(H):
    S = input()
    for j, v in enumerate(S):
        if v == '#':
            s[i+1, j+1] = 1

for i in range(H):
    ans = ''
    for j in range(W):
        if s[i+1, j+1] == 1:
            ans += '#'
        else:
            ans += str(np.sum(s[i:i+3, j:j+3], dtype=np.int))
    print(ans)


Measured memory_bytes: 12384