akhauriyash/Code-Regression huggingface dataset:
#include<stdio.h>
#define max 1000000

long long int id[4000],raw[4000];

int main(){
    long long int num,sale,d;
    int n,i,j,count,k,l,m;

    for(;;){
    
        scanf("%lld",&n);

        for (k=0;k<=4000;k++){
        
            id[k] = 0;
        }

        if(n==0)break;

        else{
            count = 0;
            for(i=1;i<=n;i++){
                scanf("%lld %lld %lld",&num,&sale,&d);
                id[num] += (sale * d);
                raw[i] = num;
            }
            for(l=0;l<4000;l++){
                for(m=l+1;m<=4000;m++){
                    if(raw[l]==raw[m])raw[m]=0;
                }
            }
            for(j=1;j < 4000;j++){
                if(id[raw[j]] >=  max){
                    printf("%lld\n",raw[j]);
                    count++;
                }
            }
        if(count==0)printf("NA\n");
        

        }
    }
  return 0;
}

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

int main()
{
    int N;
    cin >> N;
    cout << N * N * N << endl;
}

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

int main(){
    string s;
    std::cin >> s;
    bool rnow = true;
    vector<ll> result(s.length());
    ll start = 0;
    ll loca = -1;
    ll rnum =1;
    ll lnum = 0;
    for (int i = 1; i < s.length(); i++) {
        if(rnow){
            if(s[i] == 'R'){
                rnum++;
            }else{
                // RRRLのL
                loca = i;
                rnow=false;
                lnum++;
            }
        }else{
            if(s[i] == 'R'){
                // 終わり
                // 子供がcou人
                // 始まりはstart
                // rの人数
                
                result[loca-1] = (rnum+1)/2+lnum/2;
                result[loca] = (lnum+1)/2+rnum/2;
                
                // 新しい始まり
                start = i;
                rnum = 1;
                lnum = 0;
                rnow = true;
            }else{
                lnum++;
            }
        }
    }
    
    // std::cout << loca << std::endl;
    result[loca-1] = (rnum+1)/2+lnum/2;
    result[loca] = (lnum+1)/2+rnum/2;
    
    for (int i = 0; i < s.length()-1; i++) {
        std::cout << result[i]<<" ";
    }
    std::cout << result[s.length()-1] << std::endl;
}


Measured memory_bytes: 1408
//コンパイラ最適化用
#pragma GCC optimize("O3")
//インクルード(アルファベット順)
#include<algorithm>//sort,二分探索,など
#include<bitset>//固定長bit集合
#include<cmath>//pow,logなど
#include<complex>//複素数
#include<deque>//両端アクセスのキュー
#include<functional>//sortのgreater
#include<iomanip>//setprecision(浮動小数点の出力の誤差)
#include<iostream>//入出力
#include<iterator>//集合演算(積集合,和集合,差集合など)
#include<map>//map(辞書)
#include<numeric>//iota(整数列の生成),gcdとlcm(c++17)
#include<queue>//キュー
#include<set>//集合
#include<stack>//スタック
#include<string>//文字列
#include<unordered_map>//イテレータあるけど順序保持しないmap
#include<unordered_set>//イテレータあるけど順序保持しないset
#include<utility>//pair
#include<vector>//可変長配列

using namespace std;
typedef unsigned int ll;

//マクロ
//forループ関係
//引数は、(ループ内変数,動く範囲)か(ループ内変数,始めの数,終わりの数)、のどちらか
//Dがついてないものはループ変数は1ずつインクリメントされ、Dがついてるものはループ変数は1ずつデクリメントされる
#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=ll(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=ll(b);i--)
//xにはvectorなどのコンテナ
#define ALL(x) x.begin(),x.end() //sortなどの引数を省略したい
#define SIZE(x) ll(x.size()) //sizeをsize_tからllに直しておく
//定数
#define INF 1000000000000 //10^12:極めて大きい値,∞
#define MOD 1000000007 //10^9+7:合同式の法
#define MAXR 100000 //10^5:配列の最大のrange(素数列挙などで使用)
//略記
#define PB push_back //vectorヘの挿入
#define MP make_pair //pairのコンストラクタ
#define F first //pairの一つ目の要素
#define S second //pairの二つ目の要素
#define Umap unordered_map
#define Uset unordered_set

ll s[2001],t[2001],dp[2001][2001]={0};

signed main(){
    //入力の高速化用のコード
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll n,m;cin>>n>>m;
    REP(i,n){cin>>s[i];}
    REP(i,m){cin>>t[i];}
    REP(i,n+1){dp[i][0]=1;}
    REP(i,m+1){dp[0][i]=1;}
    REP(i,n){
        REP(j,m){
            if(s[i]==t[j]){
                dp[i+1][j+1]+=(dp[i+1][j]+dp[i][j+1])%MOD;
            }else{
                dp[i+1][j+1]+=(dp[i+1][j]+dp[i][j+1]-dp[i][j]+MOD)%MOD;
            }
        }
    }
    cout<<dp[n][m]<<"\n";
}

Measured memory_bytes: 19252
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

const (
	initialBufSize = 10000
	maxBufSize     = 10000000
)

var (
	sc = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		sc.Split(bufio.ScanWords)
		return sc
	}()
)

func nextString() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextFloat() float64 {
	sc.Scan()
	f, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return f
}

func cutVertical(s []string, groups map[int]int, numGroups, h, w, k int) int {
	vcuts := 0
	gok := true
	white := make([]int, numGroups)
	for j := 0; j < w; j++ {
		colWhite := make([]int, numGroups)
		ok := true
		for i := 0; i < h; i++ {
			colWhite[groups[i]] += int(rune(s[i][j]) - '0')
			white[groups[i]] += int(rune(s[i][j]) - '0')
			if colWhite[groups[i]] > k {
				gok = false
			}
			if white[groups[i]] > k {
				ok = false
			}
		}
		if !ok {
			vcuts++
			white = colWhite
		}
	}
	if gok {
		return vcuts
	}
	return math.MaxInt64 / 2
}

func grouping(mask, h int) (map[int]int, int) {
	groups := make(map[int]int)
	groups[0] = 0
	num := 0
	for i := 1; i < h; i++ {
		if mask&(1<<uint(i-1)) == 0 {
			groups[i] = groups[i-1]
		} else {
			groups[i] = groups[i-1] + 1
			num++
		}
	}
	return groups, num
}

func solve(s []string, h, w, k int) int {
	minCuts := math.MaxInt64
	for mask := 0; mask < (1 << uint(h-1)); mask++ {
		groups, hcuts := grouping(mask, h)
		vcuts := cutVertical(s, groups, hcuts+1, h, w, k)
		if hcuts+vcuts < minCuts {
			minCuts = hcuts + vcuts
		}
	}
	return minCuts
}

func main() {
	h, w, k := nextInt(), nextInt(), nextInt()
	s := make([]string, h)
	for i := 0; i < h; i++ {
		s[i] = nextString()
	}
	ans := solve(s, h, w, k)
	fmt.Println(ans)
}


Measured memory_bytes: 6528
//  Copyright 2020 Nikita Golikov

#include <bits/stdc++.h>

using namespace std;

using i64 = int64_t;
using ui64 = uint64_t;

template <class A, class B>
bool smin(A &x, B &&y) {
  if (y < x) {
    x = y;
    return true;
  }
  return false;
}

template <class A, class B>
bool smax(A &x, B &&y) {
  if (x < y) {
    x = y;
    return true;
  }
  return false;
}

i64 const INF = (i64) 1e18;

int main() {
#ifdef GOLIKOV
  assert(freopen("in", "rt", stdin));
  auto _clock_start = chrono::high_resolution_clock::now();
#endif
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  cin >> n;
  vector<string> a(n);
  vector<int> cost(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i] >> cost[i];
  }
  auto is_pal = [](string const& s) {
    auto rs = s;
    reverse(rs.begin(), rs.end());
    return s == rs;
  };
  using state = pair<string, string>;
  set<pair<i64, state>> st;
  map<state, i64> mp;
  {
    state init{};
    mp[init] = 0;
    st.emplace(0, init);
  }
  i64 ans = INF;
  auto upd_set = [&](string const& L, string const& R, i64 c) {
    state to_add{};
    if (L.size() <= R.size()) {
      to_add.second = R.substr(0, R.size() - L.size());
    } else {
      to_add.first = L.substr(R.size());
    }
    if (is_pal(to_add.first) && is_pal(to_add.second)) {
      smin(ans, c);
      return;
    }
    if (!mp.count(to_add) || mp[to_add] > c) {
      st.erase({mp[to_add], to_add});
      mp[to_add] = c;
      st.emplace(c, to_add);
    }
  };
  while (!st.empty()) {
    auto x = *st.begin();
    st.erase(st.begin());
    auto c = x.first;
    auto L = x.second.first;
    auto R = x.second.second;
    for (int i = 0; i < n; ++i) {
      auto nstr = a[i];
      auto ncost = cost[i];
      if (L.empty()) {
        int need = (int) min(nstr.size(), R.size());
        bool ok = true;
        for (int j = 0; j < need; ++j) {
          if (nstr[j] != R[(int) R.size() - j - 1]) {
            ok = false;
            break;
          }
        }
        if (ok) upd_set(nstr, R, c + ncost);
      }
      if (R.empty()) {
        int need = (int) min(nstr.size(), L.size());
        bool ok = true;
        for (int j = 0; j < need; ++j) {
          if (L[j] != nstr[(int) nstr.size() - j - 1]) {
            ok = false;
            break;
          }
        }
        if (ok) upd_set(L, nstr, c + ncost);
      }
    }
  }
  cout << (ans == INF ? -1 : ans) << '\n';

#ifdef GOLIKOV
  cerr << "Executed in " << chrono::duration_cast<chrono::milliseconds>(
      chrono::high_resolution_clock::now()
          - _clock_start).count() << "ms." << endl;
#endif
  return 0;
}


Measured memory_bytes: 3712
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define R cin>>
#define Z class
#define ll long long
#define ln cout<<'\n'
#define in(a) insert(a)
#define pb(a) push_back(a)
#define pd(a) printf("%.10f\n",a)
#define mem(a) memset(a,0,sizeof(a))
#define all(c) (c).begin(),(c).end()
#define iter(c) __typeof((c).begin())
#define rrep(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define REP(i,m,n) for(ll i=(ll)(m);i<(ll)(n);i++)
#define rep(i,n) REP(i,0,n)
#define tr(it,c) for(iter(c) it=(c).begin();it!=(c).end();it++)
template<Z A>void pr(A a){cout<<a;ln;}
template<Z A,Z B>void pr(A a,B b){cout<<a<<' ';pr(b);}
template<Z A,Z B,Z C>void pr(A a,B b,C c){cout<<a<<' ';pr(b,c);}
template<Z A,Z B,Z C,Z D>void pr(A a,B b,C c,D d){cout<<a<<' ';pr(b,c,d);}
template<Z A>void PR(A a,ll n){rep(i,n){if(i)cout<<' ';cout<<a[i];}ln;}
ll check(ll n,ll m,ll x,ll y){return x>=0&&x<n&&y>=0&&y<m;}
const ll MAX=1e9+7,MAXL=1LL<<61,dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
typedef pair<ll,ll> P;

void Main() {
  ll n,m;
  cin >> n >> m;
  int a[n][m];
  rep(i,n)rep(j,m) R a[i][j];
  ll ans=0;
  rep(i,n) {
    REP(j,i+1,n) {
      ll d=0;
      rep(k,m) d+=(a[i][k]-a[j][k])*(a[i][k]-a[j][k]);
      ll c=sqrt(d);
      if(c*c==d) ans++;
    }
  }
  pr(ans);
}

int main(){ios::sync_with_stdio(0);cin.tie(0);Main();return 0;}


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

using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long int
#define INF 1000000007
// cin.eof() 入力個数の問題
int main(){
int A,B,m;
cin>>A>>B>>m;
int a[A],b[B];
int MA=INF,MB=INF;
rep(i,A){
    cin>>a[i];
    MA=min(MA,a[i]);
}
rep(i,B){
    cin>>b[i];
    MB=min(MB,b[i]);
}
int ans=MA+MB;

int x[m],y[m],c[m];
rep(i,m){
cin>>x[i]>>y[i]>>c[i];
}

rep(i,m){
    int price=a[x[i]-1]+b[y[i]-1]-c[i];
    ans=min(ans,price);
}
cout<<ans<<endl;
  return 0;
}


Measured memory_bytes: 2176
import java.util.Scanner;
class Main {
	public static void main(String[] args){
		final int Number=100;
		try(Scanner sc = new Scanner(System.in)){
			int N = Integer.parseInt(sc.next());
			int[] A = new int[N];
			for(int i=0;i<N;i++)A[i]=Integer.parseInt(sc.next());
			System.out.print(A[0]);
			for(int j=1;j<N;j++)System.out.print(" "+A[j]);
			System.out.println();
			for(int i=1;i<N;i++){
				int v = A[i];
				for(int j = i-1;(j>=0)&&(A[j]>v);j--){
					A[j+1]=A[j];
					A[j]=v;
				}
				
				System.out.print(A[0]);
				for(int j=1;j<N;j++)System.out.print(" "+A[j]);
				System.out.println();
			}
		}
	}
}

Measured memory_bytes: 31448
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <math.h>
#include <stdio.h>
#include <vector>
using namespace std;
typedef long long ll;
int main(){
	int x,y;
	cin >> x>>y;
	cout << x + y / 2 << endl;

	return 0;
}

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

int main() {

  string in;

  while( cin >> in ) {

    for ( long long int i = 0; i < in.size(); i++ ) {

      if ( in[i] == '@' ) {
	i++;
	for ( long long int j = 0; j < in[i] - '0'; j++ ) {
	  cout << in[i+1];
	}
	i++;
      }else {
	cout << in[i];
      }

    }

    cout << endl;

  }

  return 0;

}

Measured memory_bytes: 1172
k = int(raw_input())
n = 50
a = [49] * n
c = k // n
for i in range(n):
	a[i] += c
c = k % n
for _ in range(c):
	mp = 0
	for i in range(n):
		if a[i] < a[mp]:
			mp = i
	for i in range(n):
		if i == mp:
			a[i] += n
		else:
			a[i] -= 1
print n
for i in range(n):
	print a[i],

Measured memory_bytes: 2568
//9-A

/*
 * compareToIgnoreCase
 * ????????????String.compareToIgnoreCase(String)
 * ??§????????¨?°???????????????\????????§???2 ????????????????????????????????????????????????
 * ??§????????¨?°???????????????\????????§?????????????????? String ????????? String ????????§????????´??????????????´??°???????????´?????? 0????°?????????´????????£?????´??°
*/


import java.util.Scanner;

class Main {
    public static void main(String [] args){
         
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();//????????° & ???????????°
        
        int tarou = 0;
        int hanako = 0;
       
        for( int i = 0 ; i < n ; i++ ){
        	
        	String[] ba = new String[2];
        	
        	for(int j = 0 ; j < 2 ; j++){
        		ba[j] = sc.next();
        	}
        	
        	if( ba[0].compareToIgnoreCase(ba[1]) > 0 ) {
        		tarou = tarou + 3;
        	}else if( ba[0].compareToIgnoreCase(ba[1]) < 0 ){
        		hanako = hanako + 3;
        	}else if( ba[0].compareToIgnoreCase(ba[1]) == 0 ){
        		tarou++;
        		hanako++;
        	}
        	
        }
        
        System.out.println(tarou + " " + hanako);
        
    }
}

Measured memory_bytes: 29940
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

int main() {
	int n, a, b, c;
	std::cin >> n >> a >> b >> c;
	std::vector<int> d(n);
	
	for (auto&& e : d)
		std::cin >> e;

	std::sort(d.begin(), d.end(), std::greater<int>());

	int before = c / a, krSum = 0;
	for (int i = 1; i - 1 < d.size(); ++i) {
		krSum += d[i - 1];
		if (before > (c + krSum) / (a + b*i)) {
			std::cout << before << std::endl;
			return 0;
		}
		before = (c + krSum) / (a + b*i);
	}

	std::cout << before << std::endl;
}

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

void solve(long long N, std::vector<std::string> s){
    
    int n = s.size();
    if (n==0) {
        printf(0);
        return;
    }
    for (auto& w: s){
        sort(w.begin(), w.end());
    }
    sort(s.begin(), s.end());

    long long int result = 0LL;
    long long int cur = 1LL;
    for (int i=1; i<n; ++i){
        if (s[i]==s[i-1]){
            cur++;
        } else {
            // C n take 2
            // if (cur>0)
            result += (cur*(cur-1))/2;
            cur = 1LL;
        }
    }
    if (cur>=1){
        result += (cur*(cur-1))/2;
    }
    printf("%lld", result);
}

/*
failed at b11
*/
void solve_n(long long N, std::vector<std::string> s){
    int result = 0;
    unordered_map<string, vector<string>> cache;
    for(int n = s.size(), i=n-1; i>=0; --i){
        vector<int> chars(26, 0);
        for (auto& c: s[i]){
            chars[c-'a']++;
        }
        string tmp;
        for (auto c: chars){
            tmp += to_string(c) + "_";
        }
        result += cache[tmp].size();
        cache[tmp].push_back(s[i]);
    }
    printf("%lld", result);
}

// Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
int main(){
    long long N;
    scanf("%lld",&N);
    std::vector<std::string> s(N);
    for(int i = 0 ; i < N ; i++){
        std::cin >> s[i];
    }
    solve(N, std::move(s));
    return 0;
}


Measured memory_bytes: 7296
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <algorithm>


using namespace std;



int main() {
    int m, f, r;

    while (cin >> m >> f >> r)
    {
        if (m == -1 && f ==  -1 && r == -1)
            break;

        int sum = m + f;

        if (m == -1 || f == -1)
            cout << 'F' << endl;
        else if (sum >= 80)
            cout << 'A' << endl;
        else if (sum >= 65)
            cout << 'B' << endl;
        else if (sum >= 50)
            cout << 'C' << endl;
        else if (sum >= 30)
        {
            if(r >= 50)
                cout << 'C' << endl;
            else
                cout << 'D' << endl;
        }
        else
            cout << 'F' << endl;

    }
    
    return 0;
} 

Measured memory_bytes: 3096
#include <bits/stdc++.h>
using namespace std;
 
#define DEBUG if(1)
#define MAX INT_MAX
#define MAXLL INT_MAX
#define MAXU ULLONG_MAX
#define MIN -2000000
#define endl "\n"
#define INF INT_MAX
#define MOD 1000000007
#define s(n) scanf("%d", &n)
#define ss(a,b) scanf("%d %d",&a,&b)
#define pb push_back
#define mp make_pair
#define M_PI 3.14159265358979323846
#define sz(a) int(a.size())
#define lli long long int
#define rep(i,a,n) for (int i=a;i<n;i++)
#define ler(a,n,vec) for(int i=0;i<n;i++)s(a), vec.pb(a)
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<lli,lli> ii;
#define DEBUG if(1)
#define F first
#define S second
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
int ddx[] = {1, 0};
int ddy[] = {1, 1};
#define MAXN 200010
#define MAXL 20
 
int n,kk;
vector<lli> vec;
 
lli pd[MAXN][101];
 
int main(){
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
 
  cin >> n >> kk;
  for(int i=0;i<n;i++){
  	int a;
  	cin >> a;
  	vec.pb(a);
  }
 
  for(int i=0;i<=n;i++) for(int j=0;j<=kk;j++) pd[i][j] = INT_MAX;
 
	for(int i=1;i<=kk;i++) pd[i][i] = abs(vec[i] - vec[0]);
 
  // for(int i=1;i<sz(vec);i++){
 
  // 	pd[i+1][1] = min(pd[i+1][1], pd[i][1] + abs(vec[i] - vec[i+1]));
  // 	pd[i+1][1] = min(pd[i+1][1], pd[i][2] + abs(vec[i] - vec[i+1]));
  // 	pd[i+2][2] = min(pd[i+2][2], pd[i][2] + abs(vec[i] - vec[i+2]));
  // 	pd[i+2][2] = min(pd[i+2][2], pd[i][1] + abs(vec[i] - vec[i+2]));
 
  // }

  for(int i=1;i<sz(vec);i++){
  	for(int j=1;j<=kk;j++){
  		for(int k=1;k<=kk;k++){
  			pd[i+j][j] = min(pd[i+j][j], pd[i][k] + abs(vec[i] - vec[i+j]));
  		}
  	}
  }
 
 // for(int i=0;i<sz(vec);i++){
  //	for(int j=1;j<=2;j++) cout << pd[i][j] << " ";
  	//	cout << endl;
  //}
 
 	lli ans = INT_MAX;
 	for(int i=1;i<=kk;i++) ans = min(ans, pd[n-1][i]);
 	cout << ans << endl;
 
  return 0;
}

Measured memory_bytes: 81012
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<utility>
#include<queue>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<iomanip>
#include<list>
#include<deque>
using namespace std;
//#define MODE 1
#ifdef MODE
#define DEB(X) cout<< #X <<": "<<X<<" ";
#define DEB2(X) cout<<X<<" ";
#define END cout<<endl;
#else
#define DEB(X) {}
#define DEB2(X) {}
#define END {}
#endif
typedef long long ll;
#define int ll
#define uset unordered_set
#define umap unordered_map
//typedef std::pair<int,int> P;
struct edge{int to,cost;};
const int INF=100000000000000000;
const int INF2=9223372036854775807;
const int MOD=1000000007;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
#define min(X,Y) (((int)(X)<(int)(Y))?(X):(Y))
#define max(X,Y) (((int)(X)>(int)(Y))?(X):(Y))
#define NP(X,Y) next_permutation(X,Y)
#define setdouble(X,Y) cout<<fixed<<setprecision(X)<<Y
int ceil2(int a,int b){if(a%b==0){return a/b;}else{return a/b+1;}}
int pow2(int a,int b){int r=1;for(int i=1;i<=b;i++){r*=a;}return r;}
int Log2(int a){int t=0;while(1){if(a==0||a==1){break;}a/=2;t++;}return t;}

int N;
int A[100010];
set<int> U;
map<int,int> H;
int C[5];
int B[100010];

void solve(int a,int b){
	REP(i,N){
		B[i]=0;
	}
	REP(i,N){
		if(i%3==0){
			B[i]=a;
		}
		else if(i%3==1){
			B[i]=b;
		}
		else{
			B[i]=a^b;
		}
	}
	bool flag=true;
	sort(B,B+N);
	REP(i,N){
		if(A[i]!=B[i]){
			flag=false;
		}
	}
	if(flag==true){
		cout<<"Yes"<<endl;
		exit(0);
	}
}

signed main(){
	cin>>N;
	REP(i,N){
		cin>>A[i];
		U.insert(A[i]);
		H[A[i]]++;
	}
	sort(A,A+N);
	vector<int> v(U.begin(),U.end());
	if(U.size()==4){
		cout<<"No"<<endl;
		return 0;
	}
	else if(U.size()==1){
		solve(v[0],v[0]);
	}
	else if(U.size()==2){
		solve(v[0],v[1]);
		solve(v[1],v[0]);
	}
	else{
		solve(v[0],v[1]);
		solve(v[1],v[0]);
		solve(v[1],v[2]);
		solve(v[2],v[1]);
		solve(v[0],v[2]);
		solve(v[2],v[0]);
	}
	cout<<"No"<<endl;
	return 0;
}


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



int main()
{
 
    ll x,n;
    cin>>x>>n;
    ll ar[n+1];
    ll cnt[105];
    memset(cnt,0,sizeof(cnt));
    for(int i=0;i<n;i++)
    {
        cin>>ar[i];
        cnt[ar[i]]++;
    }
    if(cnt[x]==0)
        cout<<x<<endl;
    else
    {
        ll temp=x,temp2=x;
        while(cnt[temp]!=0)
        {
            temp++;
        }
        ll right=temp;
        while(cnt[x]!=0)
        {
            x--;
        }
        ll left = x;
        if(temp2-left<=right-temp2)
        {
            cout<<left;
        }
        else
        {
            cout<<right;
        }
    }
    
    return 0;
}

Measured memory_bytes: 3636
while True:
    str = raw_input()
    list = str.split()
    n = int(list[0])
    r = int(list[1])
    if(n == 0 and r == 0):
        break
    n_list = []
    for i in xrange(n):
        n_list.append(i+1)
    for i in xrange(r):
        str = raw_input()
        list = str.split()
        p = int(list[0])
        c = int(list[1])
        n_list =  n_list[0:n-(p-1)-c] + n_list[n-(p-1):n] + n_list[n-(p-1)-c:n-(p-1)]
    print n_list[n-1]

Measured memory_bytes: 6308
#include <iostream>
#include <map>
#include <bitset>
#include <string>
#include <algorithm>
#include <vector>
#define REP(i, n) for(int i = 0; i < (n); i++)
#define ALL(c) c.begin(),c.end()
#define PB push_back
#define INF 1100000000
#define LLINF 1100000000000000000
#define MOD 1000000007
#define FI first
#define SE second
#define MP make_pair

using namespace std;
typedef long long ll;

int main()
{
  ll N;
  cin >> N;
  ll X = 1, Y = 1;
  REP(i, N) {
    ll T, A;
    cin >> T >> A;
    ll k = max((X + T - 1)/T, (Y + A - 1)/A);
    X = T*k;
    Y = A*k;
  }
  cout << (X + Y) << endl;
  return 0;
}

Measured memory_bytes: 256
/*   _/                _/                 _/_/_/   _/
  _/_/_/_/   _/_/   _/_/_/_/   _/_/    _/       _/_/
   _/     _/    _/   _/     _/    _/  _/_/_/     _/
  _/     _/    _/   _/     _/    _/  _/    _/   _/
   _/_/   _/_/       _/_/   _/_/      _/_/     _/ */
#include<iostream>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<set>
#include<map>
#include<queue>
#include<vector>
using namespace std;
using ll=long long;
const int MOD=1e9+7;
const double pi=3.14159265358979323846;
const int inf=1e9;
const ll INF=1e18;
using P=pair<int,int>;
int dx[4]={1,0,-1,0},dy[4]={0,1,0,-1};
int main() {
  cin.tie(0),cout.tie(0);
  ios::sync_with_stdio(false);
  int k,ans=0,x,y;
  cin >> k;
  for(int i=1; i<=k; i++) {
    for(int j=1; j<=k; j++) {
      for(int l=1; l<=k; l++) {
        x=__gcd(i,j);
        y=__gcd(x,l);
        ans+=y;
      }
    }
  }
  cout << ans << endl;
}

Measured memory_bytes: 3640
#include <bits/stdc++.h>
using namespace std;
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; }
typedef long long int ll;

#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
#define MOD (1000000007)
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};

int a[3];

void input(){
    for(int i=0;i<3;i++) cin >> a[i];
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    input();
    sort(a, a+3);
    cout << a[2] - a[0] << endl;
    return 0;
}

Measured memory_bytes: 256
/**
 * @author torith
 * @date 2018-10-24
 */

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int main(){

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

    int N,K;
    cin >> N >> K;

    map <int,int> cnt;

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

    int size = cnt.size();
    vector<int> vec;
    for (auto &m: cnt){
        vec.push_back(m.second);
    }
    sort(vec.begin(),vec.end());

    int ans = 0;
    int i = 0;
    while(size > K){
        size--;
        ans += vec[i++];
    }
    cout << ans << "\n";

    return 0;
}



Measured memory_bytes: 10744
#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

struct State {
  int x, y;
  State(int x, int y): x(x), y(y) {;}
};

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

int W, H;
char field[MAX_N][MAX_N];
bool visit[MAX_N][MAX_N];

int bfs(int sx, int sy, char color)
{
  queue<State> que;
  que.push(State(sx, sy));
  bool flag = true;
  int ret = 0;
  while (!que.empty()) {
    State s = que.front(); que.pop();
    int x = s.x, y = s.y;

    if (x < 0 || x >= W || y < 0 || y >= H || visit[y][x] || field[y][x] == color)
      continue;

    if (field[y][x] != '.')
      flag = false;

    visit[y][x] = true;
    ret++;

    for (int k = 0; k < 4; k++) 
      que.push(State(x + dx[k], y + dy[k]));
  }

  return flag ? ret : 0;
}

int solve(char c)
{
  memset(visit, false, sizeof(visit));
  int sol = 0, sc = 0;
  for (int i = 0; i < H; i++) {
    for (int j = 0; j < W; j++) {
      if (!visit[i][j]) {
        int val = bfs(j, i, c);
        sol += val;
        sc++;
      }
    }
  }

  return (sc > 1) ? sol : 0;
}

int main()
{
  while (cin >> W >> H && W && H) {
    for (int i = 0; i < H; i++) {
      for (int j = 0; j < W; j++) {
        cin >> field[i][j];
      }
    }

    cout << solve('B') << " " << solve('W') << endl;
  }
}

Measured memory_bytes: 916
def main():
    N = int(input())
    A = list(map(int,input().split()))
  
    if 0 in A:
        print(0)
        return
  
    prod = 1
    for a in A:
        prod *= a
        if prod > 1000000000000000000:
            print(-1)
            return
    print(prod)
    
main()

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

typedef double f64;
typedef long long i64;
typedef int i32;
typedef pair<i32, i32> pi32;
typedef unsigned long long u64;
typedef unsigned int u32;
typedef vector<i32> vi32;
typedef deque<i32> di32;

#define all(c) (c).begin(), (c).end()
#define REP(i, a, b) for (auto i = a; i < b; i++)
#define REPA(i, a, b, acc) for (auto i = a; i < b; i += acc)
#define PB push_back
#define PF push_front
#define TR(c, it) for (auto(it) = (c).begin(); (it) != (c).end(); (it)++)

i32 main() {
  ios::sync_with_stdio(false);  // Makes IO faster, remove this line if C style scanf/printf needed.

  i32 n;
  cin >> n;
  vi32 v;
  REP(i, 0, n) {
    i32 num;
    cin >> num;
    v.push_back(num);
  }
  i32 sum = accumulate(all(v), 0);
  i32 maxLen = *(max_element(all(v)));
  cout << (maxLen * 2 < sum ? "Yes" : "No") << endl;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int len;
string s;
int gx,gy;
int sx=0,sy=0;

string change(string s){
  int len=s.size();
  string res="";
  for(int i=0;i<len;i++){
    if(s[i]=='F'){
      int cnt=1;
      while(i+1<len && s[i+1]=='F'){
        i++;
        cnt++;
      }
      if(cnt%2==0)res+='f';
      else res+='F';
      
    }else{
      res+=s[i];
    }
  }
  return res;
}

int main(){
  cin>>s>>gx>>gy;

  int len=s.size();
  int p=0;
  int cc=0;
  int dir=0;
  vector<int> v,w;
  
  while(p<len){
    
    if(s[p]=='F'){
      cc++;
      p++;
    }else if(s[p]=='T'){
      if(dir==0)v.push_back(cc);
      if(dir==1)w.push_back(cc);
      dir=(dir+1)%2;
      p++;
      cc=0;
    }
  }
      if(dir==0)v.push_back(cc);
      if(dir==1)w.push_back(cc);
      /*
  for(int x:v)cout<<x<<' ';
  cout<<endl;
    for(int x:w)cout<<x<<' ';
  cout<<endl;
      */
  set<int> st;
  st.insert(0);
  for(int i=0;i<(int)v.size();i++){
    set<int> nst;
    for(int x:st){
      nst.insert( x+v[i] );
      if(i){
        nst.insert( x-v[i] );
      }
    }
    st=nst;
  }

  if(st.count(gx)==0){
    cout<<"No"<<endl;
    return 0;
  }

  st.clear();
  st.insert(0);
  for(int i=0;i<(int)w.size();i++){
    set<int> nst;
    for(int x:st){
      nst.insert( x+w[i] );
      nst.insert( x-w[i] );
    }
    st=nst;
  }

  if(st.count(gy)==0){
    cout<<"No"<<endl;
    return 0;
  }

  cout<<"Yes"<<endl;
  return 0;
}


Measured memory_bytes: 640
function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const N=input[0]-0;
  var A=input.slice(1).map(e=>{
    return e-0;
  }).sort((a,b)=>{
    return b-a;
  });
  for(var i=1;i<input.length;i++){
    if(input[i]-0===A[0]){
      console.log(A[1]);
    }else{
      console.log(A[0]);
    }
  }
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Measured memory_bytes: 60484
x = gets.to_i

case x
when 400...600 then
  puts 8
when 600...800 then
  puts 7
when 800...1000 then
  puts 6
when 1000...1200 then
  puts 5
when 1200...1400 then
  puts 4
when 1400...1600 then
  puts 3
when 1600...1800 then
  puts 2
when 1800...2000 then
  puts 1
end


Measured memory_bytes: 14316
#include<bits/stdc++.h>
using namespace std;
using ll=long long;
using data=pair<int,int>;
#define rep(i,N) for(i=0;i<N;i++)
#define rep1(i,N) for(i=1;i<N;i++)
#define mod 1000000007

long mmid(long a,long b,long c){return a<b?(b<c?b:max(a,c)):(b>c?b:min(a,c));}

ll modinv(ll a) {
  ll b=mod,u=1,v=0,t;
  while(b){
    t=a/b;
    a-=t*b; swap(a,b);
    u-=t*v; swap(u,v);
  }
  return (u+mod)%mod;
}

ll moddevide(ll a,ll b){return (a*modinv(b))%mod;}
 
ll modncr(ll n,ll r){
  ll i,plus=1;
  rep(i,r){
    plus=(plus*(n-i))%mod;
    plus=moddevide(plus,i+1);
  }
  return plus;
}

ll euclidean_gcd(ll a, ll b) {
  if(a<b) return euclidean_gcd(b, a);
  ll r;
  while ((r=a%b)){a=b;b=r;}
  return b;
}

int main(){
  ll i,j,k,N,K,cnt=0,ans;
  char ss[15];
  scanf("%s",ss);
  for(i=14;i>3;i--){
    ss[i]=ss[i-1];
  }
  ss[4]=' ';
  printf("%s\n",ss);
  return 0;
}

Measured memory_bytes: 256
import java.util.*
import java.math.*
import kotlin.math.*

fun readLn()=readLine()!!
fun readInt()=readLn().toInt()
fun readInts()=readLn().split(" ").map{it.toInt()}
fun readLong()=readLn().toLong()
fun readLongs()=readLn().split(" ").map{it.toLong()}

val out=mutableListOf<String>()
fun printLine(s:String){out.add(s)}
fun output(){println(out.joinToString("\n"))}

fun main(){
    val (n,m,q)=readInts()
    val a=Array(q+1){0}
    val b=Array(q+1){0}
    val c=Array(q+1){0}
    val d=Array(q+1){0}
    for(i in 1..q){
        val (a1,b1,c1,d1)=readInts()
        a[i]=a1-1
        b[i]=b1-1
        c[i]=c1
        d[i]=d1
    }
    val A=Array(n+1){1}
    var ans=0
    fun Gen(i:Int){
        if(i==n){
            var now=0
            for(i in 1..q){
                if(A[b[i]]-A[a[i]]==c[i])
                    now+=d[i]
            }
            ans=max(ans,now)
        }else{
            if(A[i]<m){
                A[i]++
                Gen(i)
                A[i]--
            }
            A[i+1]=A[i]
            Gen(i+1)
        }
    }
    Gen(0)
    printLine("$ans")
    output()
}

Measured memory_bytes: 40952
#pragma region
#include<bits/stdc++.h>
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define repr(i, n) for (int i = n; i > 0; i--)
#define repc(i, m, n) for (int i = m; i < n; i++)
#define reprc(i, m, n) for (int i = m; i > n; i--)
#define all(v) v.begin(), v.end()
#define INF 1e9
#define EPS 1e-10
using namespace std;
typedef long long ll;
#pragma endregion

struct pos{
    int x;
    int y;
};

int main()
{
    int N,c = 0;
    double ans = 0;
    cin >> N;
    vector<pos> p(N);

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

    vector<int> order(N);

    rep(i, N){
        order[i] = i;
    }

    do{
        rep(i, N - 1){
            int x = (p[order[i]].x - p[order[i + 1]].x);
            int y = (p[order[i]].y - p[order[i + 1]].y);
            double diff = sqrt(x * x + y * y);
            ans += diff;
        }
        c++;
    }while(next_permutation(all(order)));

    cout << fixed << setprecision(10);
    cout << ans / c << endl;
}

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

typedef long long llt;

const int MaxN = 100 + 5, MaxV = 100000 + 5;

int N, W;
llt w[MaxN]; int v[MaxN];
llt dp[MaxV];

void init() {
  scanf("%d %d", &N, &W);
  for (int i = 1; i <= N; ++i)
    scanf("%lld %d", &w[i], &v[i]);
}

void solve() {
  memset(dp, 0x7F, sizeof dp);
  dp[0] = 0;

  for (int i = 1; i <= N; ++i)
    for (int j = 100000; j >= v[i]; --j)
      dp[j] = min(dp[j], dp[j - v[i]] + w[i]);
  for (int i = 100000; i >= 0; --i)
    if (dp[i] <= W) {
      printf("%d\n", i);
      return;
    }
}

int main() {
  init();
  solve();
  return 0;
}

Measured memory_bytes: 1024
n = int(input())
a = [int(input()) for i in range(n)]
memo = [0 for i in range(n+1)]

ind = 0
cnt = 0
while 1:
    nex = a[ind]
    cnt += 1
    if nex == 2:
        print(cnt)
        break
    if memo[nex] == 1:
        print(-1)
        break
    memo[nex] = 1
    ind = nex-1

Measured memory_bytes: 7852
#include <iostream>
#include <vector>

int main(){
  int n;
  std::cin>>n;
  std::vector<unsigned int> vec(n);
  
  for(auto &v:vec) std::cin>>v;

  int cnt=0;
  for(int i=0;i<n;++i){
    int minj = i;
    for(int j=i;j<n;++j)
      if(vec[j]<vec[minj]) minj = j;
    if(i!=minj){
      cnt++;
      std::swap(vec[i],vec[minj]);
    }
  }
  std::cout<<vec[0];
  for(int i=1;i<n;++i)
    std::cout<<" "<<vec[i];
  std::cout<<"\n"<<cnt<<std::endl;
  return 0;
}

Measured memory_bytes: 3128
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

bool desc(int a, int b)
{
    return a > b;
}

int main()
{
    vector<int> vi;
    int a, b, c, d, e;
    int len;
    
    cin >> a >> b >> c >> d >> e;
    vi.push_back(a);
    vi.push_back(b);
    vi.push_back(c);
    vi.push_back(d);
    vi.push_back(e);
    
    sort(vi.begin(), vi.end());
    reverse(vi.begin(), vi.end());
    
    len = vi.size();
    for (int i = 0; i < len; i++){
        cout << vi[i];
        if (i != len - 1){
            cout << " ";
        }
    }
    cout << endl;
}

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

class Dice{
private:
  int right,left,front,back,bottom,now;
  void role(int num[6],int a,int b,string str){
    for(int i=0;i<str.size();i++){
      if(num[0]==a&&num[1]==b){
	cout<<num[2]<<endl;
	return;
      }
      switch(str[i]){
      case 'S':num[1]=now;num[0]=back;num[4]=bottom;num[5]=front;now=num[0];back=num[4];bottom=num[5];front=num[1];break;
      case 'W':num[3]=front;num[1]=right;num[2]=back;num[4]=left;front=num[1];left=num[3];back=num[4];right=num[2];break;
      case 'E':num[3]=bottom;num[0]=left;num[2]=now;num[5]=right;now=num[0];left=num[3];bottom=num[5];right=num[2];break;
      case 'N':num[4]=now;num[0]=front;num[1]=bottom;num[5]=back;now=num[0];back=num[4];bottom=num[5];front=num[1];break;
      }
     
      if(num[0]==a&&num[1]==b){
	cout<<num[2]<<endl;
	return;
      }
    }
  }
public:
  void Scan(int num[6],int a,int b){
    now=num[0];right=num[2];left=num[3];front=num[1];back=num[4];bottom=num[5];
    role(num,a,b,"WWWNWWWWNWWWWNWWWNWWWWNNWWWNWWW");
  }
};

int main(){
  Dice dice;
  int a,b,n;
  int num[6],num2[6];
  for(int i=0;i<6;i++){
    cin>>num[i];
    num2[i]=num[i];
  }
  cin>>n;
  for(int i=0;i<n;i++){
    cin>>a>>b;
    dice.Scan(num,a,b);
    for(int j=0;j<6;j++)
      num[j]=num2[j];
  }
  return 0;
}

Measured memory_bytes: 3120
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<VI> VVI;

int main() {
  int N;
  cin >> N;
  set<string> s;
  rep(i, N) {
    string ss;
    cin >> ss;
    s.insert(ss);
  }
  cout << s.size() << endl;
  return 0;
}


Measured memory_bytes: 19200
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) {
        try {
            // 標準入力
            InputStreamReader isr = new InputStreamReader(System.in);
            BufferedReader br = new BufferedReader(isr);
            String strArr[]= br.readLine().split(" ");
            long n = Long.parseLong(strArr[0]);
            long m = Long.parseLong(strArr[1]);
            if (Math.abs(n - m) >= 2) {
                System.out.println(0);
            } else if (n != m) {
                System.out.println((getFactorial(n) * getFactorial(m)) % 1000000007);
            } else {
                System.out.println((getFactorial(n) * getFactorial(m) * 2) % 1000000007);
            }
        } catch (IOException e) {
            e.printStackTrace();
           }
    }

    public static long getFactorial(long num) {
        long ret = 1;
        for (long i = 2; i <= num; i++) {
            ret = ret * i % 1000000007;
        }
        return ret;
    }
}

Measured memory_bytes: 21204
# Aizu Problem 00169: Blackjack
#
import sys, math, os, bisect

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def blackjack(hand):
    hand = [min(h, 10) for h in hand]
    S = sum(hand)
    if S > 21:
        return 0
    C = hand.count(1)
    if C == 0:
        return S
    for k in range(C):
        C -= 1
        S += 10
        if S > 21:
            return S - 10
    return S

    
while True:
    hand = [int(_) for _ in input().split()]
    if len(hand) == 1 and hand[0] == 0:
        break
    print(blackjack(hand))

Measured memory_bytes: 7784
import sys

input = sys.stdin.readline


class Bit:
    """1-indexed"""

    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

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

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


N, Q = map(int, input().split())
C = tuple(map(int, input().split()))
queries = []
for i in range(Q):
    l, r = map(int, input().split())
    queries.append((l, r, i))
queries.sort(key=lambda x: x[1])

b = Bit(N)
last = [None] * (N + 1)

cur = 1
ans = [0] * Q
for l, r, i in queries:
    while cur <= r:
        if last[C[cur - 1]] is not None:
            b.add(last[C[cur - 1]], -1)
        last[C[cur - 1]] = cur
        b.add(cur, 1)
        cur += 1
    ans[i] = b.sum(r) - b.sum(l - 1)
print(*ans, sep='\n')


Measured memory_bytes: 209968
n, k = map(int,input().split())
h = tuple(map(int, input().split()))
dp = [0]+[float('inf')]*(n-1)
for i in range(1,n):
    for j in range(max(0, i-k), i):
        dp[i] = min(dp[i], dp[j]+abs(h[j]-h[i]))
print(dp[-1])


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

int main(){
    int n, m;
    cin >> n >> m;
    int max = 0;
    int min = 100001;
    for(int i=0; i<m; i++){
        int a, b;cin >> a >> b;
        if(a > max){max = a;}
        if(b < min){min = b;}
    }
    if(min < max){
        cout << 0 << endl;
    }else{
        cout << min-max+1 << endl;
    }
}

Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#include <tuple>
#define mkp make_pair
#define mkt make_tuple
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
template<class T> void chmin(T &a,const T &b){if(a>b) a=b;}
template<class T> void chmax(T &a,const T &b){if(a<b) a=b;}

const ll INF=1e18;
map<ll,ll> mp;

ll A,B,C,D;

ll mul(ll a,ll b){
    if(a<=INF/b) return a*b;
    else return INF;
}

ll calc(ll N){
    if(N==0) return 0;
    if(N<0) return INF;
    if(mp.count(N)) return mp[N];
    //cout<<N<<endl;

    ll res=mul(N,D);
    if(N!=N/2) chmin(res,mul(N%2,D)+calc(N/2)+A);
    if(N!=(N+2)/2) chmin(res,mul(2-N%2,D)+calc((N+2)/2)+A);

    if(N!=N/3) chmin(res,mul(N%3,D)+calc(N/3)+B);
    if(N!=(N+3)/3) chmin(res,mul(3-N%3,D)+calc((N+3)/3)+B);

    if(N!=N/5) chmin(res,mul(N%5,D)+calc(N/5)+C);
    if(N!=(N+5)/5) chmin(res,mul(5-N%5,D)+calc((N+5)/5)+C);

    mp[N]=res;
    return res;
}

void solve(){
  //ll N,A,B,C,D;
  ll N;
  cin>>N>>A>>B>>C>>D;

  mp.clear();

  ll ans=calc(N);

  cout<<ans<<"\n";
}

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

  int T;
  cin>>T;
  rep(i,T) solve();

  return 0;
}


Measured memory_bytes: 4844
h, w = map(int, input().split())
maze = [['#'] * (w+2)]
cou = 0
for i in range(h):
    a = ['#'] + list(input()) + ['#']
    maze.append(a)
x = ['#'] * (w+2)
maze.append(x)

for i in range(1, h+1):
    for j in range(1, w+1):
        if maze[i][j] == '#':
            cou += 1

ng = True
pos = [[1, 1, 0]]
checklist = [[0] * (w+2) for _ in range(h+2)]
while len(pos) > 0:
    x, y, depth = pos.pop(0)
    if ([x, y] == [h, w]) & (maze[x][y] != '#'):
        ans = h * w - cou - depth - 1
        #print(cou)
        #print(depth)
        print(ans)
        ng = False
        break
    maze[x][y] = 'f'

    if (maze[x+1][y] == '.') & (checklist[x+1][y] == 0):
        pos.append([x+1, y, depth+1])
        checklist[x+1][y] = 1
    if (maze[x][y+1] == '.') & (checklist[x][y+1] == 0):
        pos.append([x, y+1, depth+1])
        checklist[x][y+1] = 1
    if (maze[x-1][y] == '.') & (checklist[x-1][y] == 0):
        pos.append([x-1, y, depth+1])
        checklist[x-1][y] = 1
    if (maze[x][y-1] == '.') & (checklist[x][y-1] == 0):
        pos.append([x, y-1, depth+1])
        checklist[x][y-1] = 1
    #print(pos)
    #print(maze)


if (len(pos) == 0) & ng:
    print(-1)

Measured memory_bytes: 40816
#include <cstdio>

int main(void)
{
    int A,B,N;
    scanf("%d%d%d",&N,&A,&B);
    if(N==1)
    {
        if(A==B)
            printf("1\n");
        else
            printf("0\n");
    }
    else if(N > 1)
    {
        if(A>B)
            printf("0\n");
        else
            printf("%lld\n",(long long )(B-A)*(N-2)+1);
    }
    else
    {
        return 0;
    }
    
    return 0;
}

Measured memory_bytes: 128
fun main(args: Array<String>) {
  val N = readInt()
  val A = readInts().sortedDescending()
  val B = readInts().sorted()
  val C = readInts().sorted()

  var sum = 0L
  B.forEach { b ->
    val aNum = A.size - A.myBinarySearch { a -> a < b }
    val cNum = C.size - C.myBinarySearch { c -> b < c }
    sum += aNum.toLong() * cNum
  }
  println(sum)
}

fun myBinarySearch(begin: Int, end: Int, isOk: (key: Int) -> Boolean): Int {
  var ng = begin
  var ok = end

  while (Math.abs(ok - ng) > 1) {
    val mid = (ok + ng) / 2
    if (isOk(mid)) {
      ok = mid
    } else {
      ng = mid
    }
  }

  return ok
}

fun <T> List<T>.myBinarySearch(isOk: (T) -> Boolean): Int {
  return myBinarySearch(-1, size) { index -> isOk(get(index)) }
}

fun <T> Array<T>.myBinarySearch(isOk: (T) -> Boolean): Int {
  return myBinarySearch(-1, size) { index -> isOk(get(index)) }
}


fun readString() = readLine()!!
fun readStrings() = readString().split(" ")
fun readInt() = readString().toInt()
fun readLong() = readString().toLong()
fun readInts() = readStrings().map { it.toInt() }
fun readLongs() = readStrings().map { it.toLong() }


Measured memory_bytes: 107036
s = gets.chomp.split("")
t = gets.chomp.split("")

s.sort!
t.sort!.reverse!

ans = false
for i in 0..(t.size - 1) do
  if s[i] && t[i]
    if s[i] < t[i]
      ans = true
      break
    elsif s[i] > t[i]
      ans = false
      break
    end
  elsif !s[i] && t[i]
    ans = true
  end
end

puts ans ? "Yes" : "No"


Measured memory_bytes: 1788
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <climits>
#include <random>
#include <iomanip>

using namespace std;
using P = pair<long, long>;

typedef long long int ll;

#define EPS (1e-7)
#define INF (1e18)
#define PI (acos(-1))

#define fillInt(xs)        \
  for (int i = 0; i < (xs).size(); i++) \
    scanf("%d", &xs[i]);
#define fillLong(xs)       \
  for (int i = 0; i < (xs).size(); i++) \
    scanf("%ld", &xs[i]);
#define fillDouble(xs)       \
  for (int i = 0; i < (xs).size(); i++) \
    scanf("%lf", &xs[i]);
#define fillString(xs)       \
  for (int i = 0; i < (xs).size(); i++) \
    cin >> xs[i];
#define sortv(xs) sort(xs.begin(), xs.end())
#define sortvinv(xs) sort(xs.begin(), xs.end(), std::greater<long>())
#define lbv(xs, x) lower_bound(xs.begin(), xs.end(), x) - xs.begin()
#define ubv(xs, x) upper_bound(xs.begin(), xs.end(), x) - xs.begin()
#define bs(xs, x) binary_search(xs.begin(), xs.end(), x)
#define index_of(as, x) \
  distance(as.begin(), lower_bound(as.begin(), as.end(), x))
#define rad_to_deg(rad) (((rad)/2/M_PI)*360)
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define concat(xs, ys) (xs).insert((xs).end(), (ys).begin(), (ys).end())

const int mod = 1000000007;
const int MAX_V = 100005;

bool used[MAX_V];
vector<int> G[MAX_V];

int colors[2005][2005];
int colorsSum[2005][2005];

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

  long n, k;
  cin >> n >> k;

  rep(i, n) {
    long x, y;
    char c;
    cin >> x >> y >> c;
    if (c == 'W') {
      colors[x % (2*k)][y % (2*k)] += 1;
    } else {
      colors[(x + k) % (2*k)][y % (2*k)] += 1;
    }
  }

  rep(i, 2*k) rep(j, 2*k) {
    colorsSum[i+1][j+1] += colors[i][j];
    colorsSum[i+1][j+1] += colorsSum[i+1][j];
    colorsSum[i+1][j+1] += colorsSum[i][j+1];
    colorsSum[i+1][j+1] -= colorsSum[i][j];
  }

  long res = 0;
  rep(i, k) rep(j, k){
    long tmp = 0;
    tmp += colorsSum[2*k][2*k];
    tmp += colorsSum[i+1+k][j+1+k];
    tmp -= colorsSum[2*k][j+1+k];
    tmp -= colorsSum[i+1+k][2*k];
    tmp += colorsSum[2*k][j+1];
    tmp += colorsSum[i+1][2*k];
    tmp += colorsSum[i+1+k][j+1+k];
    tmp -= colorsSum[i+1][j+1+k];
    tmp -= colorsSum[i+1][j+1+k];
    tmp -= colorsSum[i+1+k][j+1];
    tmp -= colorsSum[i+1+k][j+1];
    tmp += colorsSum[i+1][j+1];
    tmp += colorsSum[i+1][j+1];
    res = max(res, tmp);
    res = max(res, n-tmp);
  }
  cout << res << endl;
}


Measured memory_bytes: 34048
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define all(a)  (a).begin(),(a).end()
#define pb push_back
#define INF (1e9+1)
//#define INF (1LL<<59)
 
 
int main(){
    int h,w;
    cin>>h>>w;
    vector<string> vs(h);
    rep(i,h)cin>>vs[i];
     
    int ans = 0;
    rep(i,h){
        rep(j,w){
            if(i==0)continue;
            if(vs[i][j]!='-')continue;
            if( (j!=0 && vs[i][j-1]=='o') || (j!=w-1 && vs[i][j+1]=='o') )continue;
             
            int dy[]={-1,-1,-1,0,1,1,1,0};
            int dx[]={-1,0,1,1,1,0,-1,-1};
 
            bool f = true;
            rep(k,8){
                int ddy = i+dy[k];
                int ddx = j+dx[k];
                if(  ddx>=0 && ddy>=0 && ddx<w && ddy<h && vs[ddy][ddx]=='x' )f=false;
            }
            if(f)ans++;
        }
    }
    cout<<ans<<endl;
}

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

typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> ii;
typedef tuple<ll, ll, ll> iii;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef vector<iii> viii;
typedef vector<vi> vvi;
typedef vector<vii> vvii;
#define REP(i,n) for (ll i = 0; i < n; ++i)
#define REPR(i,n) for (ll i = n-1; i >= 0; --i)
#define FOR(i,m,n) for (ll i = m; i < n; ++i)
#define FORR(i,m,n) for (ll i = n-1; i >= m; --i)
#define FORE(x,xs) for (const auto& x : xs)
#define ALL(v) v.begin(), v.end()

int A, B;

int main() {
    cin >> A >> B;
    cout << 6 - A - B << endl;
}

Measured memory_bytes: 256