akhauriyash/Code-Regression huggingface dataset:
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RankNTypes #-}
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Maybe
import Data.List
-- import qualified Data.Vector.Unboxed as VU
-- import qualified Data.Vector.Unboxed.Mutable as VUM
-- import Control.Monad
-- import Control.Monad.ST
-- import Debug.Trace
-- trace _ = id

solve :: Int -> [(Int,Int)] -> Int
solve bN abs | null aMore = 0
             | otherwise = s - b0
  where
    aMore = [(a,b) | (a,b) <- abs, a > b]
    (_, b0) = minimumBy f aMore
    f (_,b) (_,b') | b < b' = LT
                   | b == b' = EQ
                   | b > b' = GT
    s = sum (map fst abs)

readBInt :: B.ByteString -> Int
readBInt = fst . fromJust . B.readInt

tmain :: B.ByteString -> Int
tmain cont =
  let remLines0 = map B.words (B.lines cont)
      [bs_bN]:remLines1 = remLines0
      bN = readBInt bs_bN
      abs = map (\[x1,x2] -> (readBInt x1,readBInt x2)) remLines1
  in solve bN abs

outAnswer :: Int -> IO ()
outAnswer = putStrLn . show

main :: IO ()
main = outAnswer . tmain =<< B.getContents

-------------------------------------------------------------------------------

inp1 = "2\n1 2\n3 2\n"
inp2 = "3\n8 3\n0 1\n4 8\n"
inp3 = "1\n1 1\n"
tv1 = tmain $ B.pack inp1
tv2 = tmain $ B.pack inp2
tv3 = tmain $ B.pack inp3
test1 = tv1 == 2
test2 = tv2 == 9
test3 = tv3 == 0
alltest = test1 && test2 && test3


Measured memory_bytes: 6908
def gcd(a, b):
  if a%b == 0:
    return(b)
  else:
    return(gcd(b, a%b))

def gcd3(a,b,c):
  d = gcd(a,b)
  ans = gcd(d,c)
  return ans

def main():
  K = int(input())

  ans = 0

  for i in range(K):
    for j in range(K):
      for k in range(K):
        ans += gcd3(i+1,j+1,k+1)

  print(ans)

if __name__ == "__main__":
  main()

Measured memory_bytes: 76636
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int n = 2e5+5;

ll N, K;
ll A[n];
int main(){
	cin >> N;
	ll s =0;
	for(int i = 0; i < N; ++i){
		cin >> A[i+1];
		A[i+1] += A[i];
	}
	ll mD = abs(A[N] - 2*A[0]);
	for(int i =1; i <= N; ++i){
		mD = min(mD, abs(A[N] - 2*A[i]));
	}
	cout << mD << endl;
}


Measured memory_bytes: 1792
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,x,t,a,b,A;
    cin>>n>>x>>t;
    a=n%x;
    b=n/x;
    if(a==0)
    A=t*b;
    else
    A=t+t*b;
    
    cout<<A;
  }


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

using namespace std;

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

using ll = long long;
using ld = long double;

const ll INF = 1e18;
const int Inf = 1e9;
const double EPS = 1e-9;
const ll MOD = 1e9 + 7;

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(0);
    int a;
    cin >> a;
    cout << a + a * a + a * a * a << endl;
    
    return 0;
}



Measured memory_bytes: 3600
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main(){
  int N;
  cin >> N;
  
  int n = (int)log10(N) + 1;
  
  vector<char> V(n);
  for(int i = 0; i < n; i++){
    int z = N % 10;
    //cout << z << endl;
    N /= 10;
    V[i] = z+'0';
  }
  
  bool ispal = true;
  for(int i = 0; i < n/2; i++){
    if(V[i] != V[V.size() - i - 1]) ispal = false;
  }
  
  if(ispal) cout << "Yes";
  else cout << "No";
}


Measured memory_bytes: 256
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    N = int(readline())
    A = list(map(int, readline().split()))

    s = 0

    for x in A:
        s += 1 / x

    print(1 / s)


if __name__ == '__main__':
    main()


Measured memory_bytes: 61976
def solve(N, P):
    xs = [0] * N
    for i, x in enumerate(P):
        xs[x - 1] = i
    r = 0
    c = 0
    p = -1
    for i, x in enumerate(xs):
        if p < x:
            c += 1
            r = max(r, c)
        else:
            c = 1
        p = x
    return N - r

N = int(input())
P = [int(input()) for _ in range(N)]

print(solve(N, P))


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

int main() {
	int S,h,m,s;

	cin >> S;
	h = S / 3600;
	m = (S % 3600) / 60;
	s = (S % 3600) % 60;
	cout << h << ":" << m << ":" << s << endl;

	return 0;
}

Measured memory_bytes: 1164
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int main() {
  long long hp, cnt = 1, ans = 0;
  cin >> hp;
  while (hp) {
    ans += cnt;
    hp /= 2;
    cnt *= 2;
  }

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

Measured memory_bytes: 256
#include <iostream>

#include <fstream>

#include <vector>
#include <set>
#include <string>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <queue>

#include <algorithm>
#include <iomanip>
#include <cmath>
#include <random>
#include <cstdlib>
#include <ctime>
#include <utility>

using namespace std;

ifstream in("input.txt");
ofstream out("output.txt");

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

#define F first
#define S second
#define forcin(n, a) for(int i = 0; i < n; ++i) {cin >> a[i];}
#define forcout(n, a) for(int i = 0; i < n; ++i) {cout << a[i] << " ";}
#define PI acos(-1)
#define forup(st, fin) for(int i = st; i < fin; ++i)
#define fordown(st, fin) for(int i = st; i >= fin; --i)
#define reverse_all(v) reverse(v.begin(), v.end())
#define sort_all(v) sort(v.begin(), v.end())
#define sort_allr(v) sort(v.rbegin(), v.rend())

///#define cin in
///#define cout out
///#define int long long

const ll MAXL = 1e18;
const int N = 10005000;
const int MAXN = 1e9 + 7;


signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    srand(time(NULL));
    int n;
    cin >> n;
    vector<int> dp(n + 1, MAXN);
    dp[0] = 0;
    for (int i = 1; i <= n; ++i) {
        dp[i] = i;
    }
    vector<int> add_6, add_9;
    int temp = 6;
    while (temp <= n) {
        add_6.push_back(temp);
        temp *= 6;
    }
    temp = 9;
    while (temp <= n) {
        add_9.push_back(temp);
        temp *= 9;
    }
    for (int i = 1; i <= n; ++i) {
        for (auto now : add_6) {
            if (now > i) break;
            dp[i] = min(dp[i], dp[i - now] + 1);
        }
        for (auto now : add_9) {
            if (now > i) break;
            dp[i] = min(dp[i], dp[i - now] + 1);
        }
    }
    cout << dp.back() << "\n";
    return 0;
}

/*

 */

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
int main(){
	long long n,m;
	cin>>n>>m;
	if(n==m||n%m==0){
		cout<<'0';
	}
	else{
		n=n%m;
		vector<long long>v;
		for(long long i=0;i<2;i++){
		n=abs(n-m);
		v.push_back(n);
		}
		sort(v.begin(), v.end()); 
		cout<<v[0];
	}
	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin>>n;
  n = n%10;
  string s;
  switch(n)
  {
      case 0:s = "pon";
      		break;
      case 1:s = "pon";
      		break;
      case 6:s = "pon";
      		break;
      case 8:s = "pon";
      		break;
      case 2:s = "hon";
      		break;
      case 4:s = "hon";
      		break;
      case 5:s = "hon";
      		break;
      case 7:s = "hon";
      		break;
      case 9:s = "hon";
      		break;
      case 3:s = "bon";
      		break;
  }
  cout<<s;
  return 0;
}

Measured memory_bytes: 3604
#define _USE_MATH_DEFINES


#include <iostream>
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <numeric>
#include <array>
#include <set>
#include <sstream>
#include <cmath>

using namespace std;

typedef long long LL;


vector<vector<LL>> creat_matrix(LL h, LL w) {
	LL _temp;
	vector<vector<LL>> mat;
	for (LL i = 0; i < h; ++i) {
		vector<LL> vec;
		for (LL j = 0; j < w; ++j) {
			cin >> _temp;
			vec.emplace_back(_temp);
		}
		mat.emplace_back(vec);
	}
	return mat;
}


vector<vector<LL>> inner_product(vector<vector<LL>> X, vector<vector<LL>> Y) {
	size_t n = X.size();
	size_t m = X[0].size();
	size_t l = Y[0].size();

	vector<vector<LL>> mat(n, vector<LL>(l, 0));
	for (LL i = 0; i < n; ++i) {
		for (LL j = 0; j < m; ++j) {
			for (LL k = 0; k < l; ++k) {
				mat[i][k] += X[i][j] * Y[j][k];
			}
		}
	}
	return mat;
}


void show_matrix(vector<vector<LL>> mat) {
	size_t len = mat[0].size();
	for (auto&& t : mat) {
		for (LL i = 0; i < len; ++i) {
			printf("%d", t[i]);
			if (i != (len - 1)) printf(" ");
		}
		printf("\n");
	}
}


int main() {
	string p, s;
	cin >> p >> s;

	auto x = p + p;

	if (x.find(s) != string::npos) {
		printf("Yes\n");
	}
	else {
		printf("No\n");
	}

	return 0;
}



Measured memory_bytes: 3212
dishes = []
for i in range(5):
    tmp = int(input())
    rank = 10 if tmp % 10 == 0 else tmp % 10
    dishes.append([rank, tmp])
s_dished = sorted(dishes, reverse=True)

time = 0
for idx,item in enumerate(s_dished):
    time += item[1] + 10 - item[0]

time -= 10 - s_dished[4][0]

print(time)



Measured memory_bytes: 3060
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    int i,j,m,n,a,b,k,s,c,d;
    while(~scanf("%d %d %d %d",&a,&b,&c,&d))
    {
       if(a>b)
       printf("%d\n",b*c+(a-b)*d);
       else
        printf("%d\n",a*c);
    }
    return 0;
}


Measured memory_bytes: 128
// tested by Hightail - https://github.com/dj3500/hightail
import std.stdio, std.string, std.conv, std.algorithm;
import std.range, std.array, std.math, std.typecons, std.container, core.bitop;
import std.datetime, std.bigint;

int n, k;
int[] l;

void main() {
    scan(n, k);
    l = readln.split.to!(int[]);
    l.sort!"a > b"();
    writeln(l.take(k).sum);
}

void scan(T...)(ref T args) {
    string[] line = readln.split;
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}


void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}

Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
#include <vector>
typedef long long ll;
using namespace std;

int main(void){
    int b[3],N,i,j,k;
  for(i=0;i<3;i++)cin>>b[i];
  cin>>N;
  sort(b,b+3);
  
  int ans=0;
  int n,m[3];
  for(i=0;i<3;i++)m[i]=N/b[i]+1;
  for(i=0;i<m[2];i++){
    n=N-i*b[2];
    if(n<0)break;
    for(j=0;j<m[1];j++){
      if(n%b[0]==0)ans++;
      n-=b[1];
      if(n<0)break;
    }
  }

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

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

int main(void)
{
    // int x;
    // scanf("%d", &x);
    // printf("%d\n", x);

    // long x;
    // scanf("%ld", &x);
    // printf("%ld\n", x);

    // char array[x];

    char str[3];
    scanf("%s", str);

    if (strcmp(str,"ABC")==0)
        puts("ARC");
    
    if (strcmp(str,"ARC")==0)
        puts("ABC");
    
    return 0;
}

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

const int mod = 1000000007;
const int max = 510000;

long long fact[max], fact_inv[max], inv[max];

void init_comb()
{
    fact[0] = fact[1] = 1;
    fact_inv[0] = fact_inv[1] = 1;
    inv[1] = 1;

    for (int i = 2; i < max; i++) {
        fact[i] = fact[i - 1] * i % mod;
        inv[i] = mod - inv[mod % i] * (mod / i) % mod;
        fact_inv[i] = fact_inv[i - 1] * inv[i] % mod;
    }
}

long long comb(int n, int k)
{
    if (n < k) {
        return 0;
    }

    if (n < 0 || k < 0) {
        return 0;
    }

    return fact[n] * (fact_inv[k] * fact_inv[n - k] % mod) % mod;
}

int main()
{
    init_comb();
    int n, m, k;
    std::cin >> n >> m >> k;

    long long ans = 0;

    long long comb_value = comb(n * m - 2, k - 2);
    for (int x_distance = 1; x_distance < m; x_distance++) {
        ans += ((m - x_distance) * n * n % mod * comb_value % mod * x_distance % mod) % mod;
        ans %= mod;
    }

    for (int y_distance = 1; y_distance < n; y_distance++) {
        ans += ((n - y_distance) * m * m % mod * comb_value % mod * y_distance % mod) % mod;
        ans %= mod;
    }

    std::cout << ans << std::endl;
}


Measured memory_bytes: 12288
#include <stdio.h>
int main(void) {
	long long n, k, a, b, j, y;
	scanf("%lld", &n);
	scanf("%lld", &k);
	long long v;
	v = 2;
	j = k % v;
	a = n % k;
	b = (n - a) / k;
	if (j == 1) printf("%lld", b*b*b);
	else {
		y = k / v;
		if (a < y) printf("%lld", b*b*b+b*b*b);
		else printf("%lld", b*b*b + (b + 1)*(b + 1)*(b + 1));
	}
	return 0;
}

Measured memory_bytes: 128
N,K=map(int,input().split())
lis=[0]*N
for i in range(K):
  n=input()
  li=list(map(int,input().split()))
  for j in li:
    lis[j-1]=1
ans=0
for i in lis:
  if i==0:
    ans+=1
print(ans)

Measured memory_bytes: 9208
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

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

typedef long long ll;

int SURP = 1000000007;

int main(){
	int a,b;
	cin >> a >> b;

	int diff = b - a;

	int tall = 0;
	REP(i,diff+1){
		tall += i;
	}

	int ret = tall - b;
	cout << ret << endl;
	return 0;
}




Measured memory_bytes: 256
def check(a, b, c, word):
  if word == 'a':
    if not a:
      print('A')
      exit()
    check(a, b, c, a.pop(0))
  elif word == 'b':
    if not b:
      print('B')
      exit()
    check(a, b, c, b.pop(0))
  elif word == 'c':
    if not c:
      print('C')
      exit()
    check(a, b, c, c.pop(0))

a,b,c=list(input()),list(input()),list(input())
check(a, b, c, a.pop(0))

Measured memory_bytes: 9120
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const double pi=acos(-1),eps=1e-8;
const int maxn = 1<<17;
const int mod = 1e9+7;
ll gcd(ll a,ll b)
{
    return b?gcd(b,a%b):a;
}
int coutt[4][2]= {{0,1},{1,0},{-1,0},{0,-1}};
int a[100006];
int main()
{
	int l,r;
	int d;
	cin>>l>>r>>d;
	cout<<r/d-(l-1)/d<<endl; 
 	return 0;
}

Measured memory_bytes: 3620
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define ll long long
#define ld long double
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
using P=pair<long long,long long>;
#define rep(i,n) for(long long i=0; i<(long long)n; i++)
#define FOR(i,a,b) for(long long i=a; i<b; i++)
#define all(x) (x).begin(), (x).end()
#define SZ(x) ((long long)(x).size())
#define COUT(x) cout << x << endl
#define PB push_back
#define MP make_pair
#define F first
#define S second
#define vint vector<int>
#define vvint vector<vector<int>>
#define vstr vector<string>
#define vp vector<pair<int,int>>
#define vb vector<bool>
#define vvb vector<vector<bool>>
#define SUM(x) accumulate(x.begin(),x.end(),0)
#define MAX(x) *max_element(x.begin(),x.end())
#define MIN(x) *min_element(x.begin(),x.end())
#define couty cout<<"Yes"<<endl
#define coutn cout<<"No"<<endl
#define coutY cout<<"YES"<<endl
#define coutN cout<<"NO"<<endl
#define yn(x) cout<<(x?"Yes":"No")<<endl
#define YN(x) cout<<(x?"YES":"NO")<<endl
long long gcd(long long a,long long b){return b?gcd(b,a%b):a;}
long long lcm(long long a, long long b){return a*b/gcd(a,b);}
const long long dx[4]={1,0,-1,0};
const long long dy[4]={0,1,0,-1};
const long long INF = 1e12;
const long long MOD = 1e9+7;

signed main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout<<fixed<<setprecision(15);

    int n; cin >> n;
    vint a(n);
    rep(i,n) cin >> a[i];

    int wa=0,exor=0,right=0;
    int res=0;

    rep(left,n){
        while(right<n && ((wa+a[right])==(wa^a[right]))){
            wa+=a[right];
            //exor^=a[right];
            right++;
        }
        res+=right-left;
        if(left==right) right++;
        else{
            wa-=a[left];
            //exor^=a[left];
        }
    }   
    cout<<res<<endl;
}

Measured memory_bytes: 4764
def main():
	S = input()
	pattern_exist = True
	while S:
		if S.startswith("dreamer"):
			if len(S) == 7:
				break
			if S[7:].startswith("dream") or S[7:].startswith("erase"):
				S = S[7:]
				continue
		if S.startswith("dream"):
			S = S[5:]
			continue
		if S.startswith("eraser"):
			if len(S) == 6:
				break
			if S[6:].startswith("dream") or S[6:].startswith("erase"):
				S = S[6:]
				continue
		if S.startswith("erase"):
			S = S[5:]
			continue
		pattern_exist = False
		break
	if pattern_exist:
		print("YES")
	else:
		print("NO")


if __name__ == '__main__':
	main()

Measured memory_bytes: 3188
#include<iostream>
#include<map>
#include<algorithm>
#include<cmath>
#include<vector>
#include<iomanip>
#include<math.h>
#include<deque>
typedef long long ll;
ll inf = 1e9;
using namespace std;
ll dp[10000000] = {};
ll h[100005];
ll a[200005];
pair<int, int>v[100005];
int main() {
	ll n;
	cin >> n;
	deque<int> A;
	
	int x;
	for (int i = 0; i < n; i++) {
		cin >> x;
		if (i % 2 == (n - 1) % 2) {
			A.push_front(x);
		}
		else {
			A.push_back(x);
		}
	}

	for (int i = 0; i < n; i++) {
		cout<<A[i]<<" ";
	}
	cout << endl;
	return 0;
}

Measured memory_bytes: 3072
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Main m = new Main();
		m.run();
	}

	Scanner sc = new Scanner(System.in);

	void run() {

		int n = sc.nextInt();
		int m = sc.nextInt();
		
		int max = 0;
		
		for(int i = 1; i <= Math.sqrt(m)+0.0001; i++){
			if(m % i == 0){
				if(m/i >= n){
					max = Math.max(max, i);
				}
				if(i >= n){
					max = Math.max(max, m/i);
				}
			}
		}
		System.out.println(max);
		
	}
}


Measured memory_bytes: 25172
n = int(input())
a = list(map(int, input().split()))

result = 0
mode = 0
for i in range(1, n):
	if a[i] == a[i - 1]:
		if mode == 0:
			result += 1
			mode = 1
		else:
			mode = 0
	else:
		mode = 0

print(result)

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

int n;


int last(std::string s){
    int count = 0;
    for(int i=0;i<n-1;i++){
        if(s[i]!=s[i+1])count++;
    }
    return count+1;
}

int main()
{
    std::cin>>n;
    std::string s;
    std::cin>>s;
    std::cout<<last(s)<<std::endl;
}

Measured memory_bytes: 512
import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        
        int n = scan.nextInt();
        int a = scan.nextInt();
        
        int d = n % 500;
        
        if(a >= d) System.out.println("Yes");
        else System.out.println("No");
        
    }
}


Measured memory_bytes: 21844
#include<stdio.h>

int binarySearch(int A[], int key, int n) {
	int left = 0;
	int right = n;

	while( left < right ) {
		int mid = (left + right) / 2;
		 if (A[mid] == key) return mid;
		 else if (A[mid] < key) left = mid + 1;
		 else right = mid;
	}

	return 0; 
}


int main() {
	int A[100000 + 1], i, n, q, key, sum = 0;

	scanf("%d", &n);
	for (i = 0; i < n; i++) scanf("%d", &A[i]);

	scanf("%d", &q);
	for (i = 0; i < q; i++) {
		scanf("%d", &key);
		if (binarySearch(A, key, n)) sum++;	
	}

	printf("%d\n", sum);

	return 0;

}

Measured memory_bytes: 3088
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+5;
ll n,k;
ll a[200005];
ll q[1000005],ind[N],r=0,f[N][50],pre[N],nxt[N];
//倍增跳的行数
int main(){
    ios::sync_with_stdio(false);
    cin>>n>>k;k--;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if(!pre[a[i]])pre[a[i]]=i;
    }
    f[n+1][0]=1;
    for(int i=n;i>=1;i--){
        if(!nxt[a[i]]){
            f[i][0]=pre[a[i]]+1;
        }else{
            f[i][0]=f[nxt[a[i]]+1][0];
        }
        nxt[a[i]]=i;
    }
    for(int j=1;j<=40;j++){
        for(int i=1;i<=n+1;i++){
            f[i][j]=f[f[i][j-1]][j-1];
        }
    }
    int now=1;
    for(int i=40;i>=0;i--){
        if((1ll<<i)<=k)k-=1ll<<i,now=f[now][i];
    }
    for(int i=now;i<=n;i++){
        if(ind[a[i]]){
            int p=ind[a[i]];
            for(int j=ind[a[i]];j<=r;j++)
                ind[q[j]]=0;
            r=p-1;
        }else{
            q[++r]=a[i];
            ind[a[i]]=r;
        }
    }
    for(int i=1;i<=r;i++)cout<<q[i]<<' ';
}

Measured memory_bytes: 89600
import sys
from collections import deque

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


# https://at274.hatenablog.com/entry/2018/02/03/140504
class WeightedUnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n + 1)]
        self.rank = [0] * (n + 1)
        # 根への距離を管理
        self.weight = [0] * (n + 1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            y = self.find(self.par[x])
            # 親への重みを追加しながら根まで走査
            self.weight[x] += self.weight[self.par[x]]
            self.par[x] = y
            return y

    # 併合
    def union(self, x, y, w):
        rx = self.find(x)
        ry = self.find(y)
        # xの木の高さ < yの木の高さ
        if self.rank[rx] < self.rank[ry]:
            self.par[rx] = ry
            self.weight[rx] = w - self.weight[x] + self.weight[y]
        # xの木の高さ ≧ yの木の高さ
        else:
            self.par[ry] = rx
            self.weight[ry] = -w - self.weight[y] + self.weight[x]
            # 木の高さが同じだった場合の処理
            if self.rank[rx] == self.rank[ry]:
                self.rank[rx] += 1

    # 同じ集合に属するか
    def same(self, x, y):
        return self.find(x) == self.find(y)

    # xからyへのコスト
    def diff(self, x, y):
        return self.weight[x] - self.weight[y]


def main():
    N, M, *LRD = map(int, read().split())

    uf = WeightedUnionFind(N)
    for l, r, d in zip(*[iter(LRD)] * 3):
        l -= 1
        r -= 1
        if uf.same(l, r) and uf.diff(l, r) != d:
            print('No')
            return
        else:
            uf.union(l, r, d)

    print('Yes')
    return


if __name__ == '__main__':
    main()


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

using namespace std;
using ll = long long;
using ld = long double;
using ii = pair<ll, ll>;
using vi = vector<ll>;
using vb = vector<bool>;
using vvi = vector<vi>;
using vii = vector<ii>;
using vvii = vector<vii>;

constexpr int INF = 2000000000;
constexpr ll LLINF = 9000000000000000000;

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	
	int n, m;
	cin >> n >> m;
	
	vi a(n, 0LL);
	for (ll &v : a) cin >> v, --v;

	ll cost = 0LL;
	vi pf(m, 0LL), c(m, 0LL);
	for (int i = 1; i < n; ++i) {
		if (a[i - 1] <= a[i]) {
			cost += a[i] - a[i - 1];
			pf[a[i - 1] + 1] -= a[i - 1];
			c[a[i - 1] + 1]++;
			if (a[i] + 1 < m) pf[a[i] + 1] += a[i - 1], c[a[i] + 1]--;
		} else {
			cost += a[i] - (a[i - 1] - m);
			if (a[i - 1] + 1 < m)
				pf[a[i - 1] + 1] -= a[i - 1], c[a[i - 1] + 1]++;
			pf[0] -= a[i - 1] - m, c[0]++;
			pf[a[i] + 1] += a[i - 1] - m, c[a[i] + 1]--;
		}
	}

	partial_sum(pf.begin(), pf.end(), pf.begin());
	partial_sum(c.begin(), c.end(), c.begin());
	ll ans = LLINF;
	for (ll i = 0; i < m; ++i) {
		ans = min(ans, cost - (c[i] * i + pf[i]) + c[i]);
	}
	cout << ans << endl;
	
	return 0;
}


Measured memory_bytes: 2560
#include <bits/stdc++.h>
using namespace std;
typedef bool boool;
typedef long long ll;
#define vl vector<ll>
#define vb vector<boool>
#define vs vector<string>
#define vp vector<pair<ll, ll>>
#define vvl vector<vector<ll>>
#define vvp vector<vector<pair<ll, ll>>>
#define mod 1000000007
#define all(x) x.begin(), x.end()
#define rep1(i, n) for (long long i=0; i<(long long)(n); i++)
#define rep2(i, s, e) for (long long i=(s); i<(long long)(e); i++)
#define GET_MACRO(_1,_2,_3,NAME,...) NAME
#define rep(...) GET_MACRO(__VA_ARGS__, rep2, rep1)(__VA_ARGS__)


int main(){
  int n, k;
  cin >> n >> k;
  string str;
  cin >> str;
  string ans = "";
  rep(i, n){
    if(i == k-1){
      if(str[i] == 'A') ans += 'a';
      if(str[i] == 'B') ans += 'b';
      if(str[i] == 'C') ans += 'c';
    }else{
      ans += str[i];
    }
  }
  cout << ans << endl;
  return 0;
}


Measured memory_bytes: 3604
#include<bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define ii pair<int,int>
#define all(x) (x).begin(),(x).end()
#define INF 100000000000000000
#define modulo 1000000007
#define mod 998244353
#define int long long int
using namespace std;

int32_t main(){
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
   //   freopen("q.gir","r",stdin);
   //   freopen("q.cik","w",stdout);
      int X;
      cin>>X;
      int w=X%100;
      if(w<=5*(X/100))cout<<1;
      else cout<<0;
}


Measured memory_bytes: 256
/*
How to lambda
  ex) sort(ALL(cont),[](dat a,dat b){return a.l<b.l;});
lower_bound/upper_bound
  1 2 2 2 3 3 
    ^lb   ^ub */
#include <bits/stdc++.h>
#define BR "\n"
#define REP(i,n) for(int (i)=0;(i)<(n);++(i))
#define ALL(cont) begin(cont),end(cont)
#define AS_MOD(a,b) ((((a) % (b) ) + (b)) % (b))
#define FEACH(it,cont) for(auto (it) = begin(cont); it!=end(cont);++it)
#define FEACHR(it,cont) for(auto (it) = rbegin(cont); it!=rend(cont);++it)
#define pb push_back
#define pob pop_back
#define fi first
#define se second
#define getll() ([](){ll s;scanf("%lld", &s);return s;})()
#define getld() ([](){ld s;scanf("%Lf", &s);return s;})()
#define prl(P) printf("%lld", P)
#define prd(P) printf("%.10Lf", P)
#define pr(P) printf(P)
#define assign_if_greater(V, T) V=max(V,T)
using namespace std;
typedef long long ll;
typedef long double ld;
int A,B,Q;
vector<ll> As,Bs,Qs;
ll INF=(ll)1000*1000*1000*1000;
int main() {
  vector<char> buf(1<<24);
  vector<char> obuf(1<<24);
  fread(&buf[0],1,buf.size(),stdin);
  //vector<char>().swap(buf);
  istringstream stream(&buf[0]);
  stringstream ostream;

  cout << fixed << setprecision(15);
  stream >> A >> B >> Q;
  As.resize(A);Bs.resize(B);Qs.resize(Q);
  REP(i,A)
    stream >> As[i];
  REP(i,B)
    stream >> Bs[i];
  REP(i,Q) {
    ll x;
    stream >> x;
    auto ita=lower_bound(ALL(As),x);
    auto itb=lower_bound(ALL(Bs),x);
    // only go left
    ll ans=INF;
    vector<ll> alis,blis;
    if (ita!=As.end()) {
      alis.pb(*ita);
    }
    if (itb!=Bs.end()) {
      blis.pb(*itb);
    }
    if (ita!=As.begin()) {
      ita--;
      alis.pb(*ita);
    }
    if (itb!=Bs.begin()) {
      itb--;
      blis.pb(*itb);
    }
    for(ll a:alis)
      for(ll b:blis) {
        ans = min(ans,abs(a-x)+abs(b-a));
        ans = min(ans,abs(b-x)+abs(b-a));
      }
    ostream << ans << BR;
  }
//obuf.shrink_to_fit();
  string o=ostream.str();
  fwrite(o.c_str(),1,o.size(),stdout);


  return 0;
}


Measured memory_bytes: 42740
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef vector<string> vs;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef pair<int,pii> pip;
typedef vector<pip>vip;
const double PI=acos(-1);
const double EPS=1e-8;
const int inf=1e8;
int out;
int in[4][2];
vvi fil;
void f(int a){
	if(a==16){
		out++;
		return;
	}
	int x=a/4,y=a%4;
	if(fil[x][y]){
		f(a+1);
		return;
	}
	rep(i,4){
		int nx=x+in[i][1];
		int ny=y+in[i][0];
		if(nx<0||ny<0||nx>=4||ny>=4||fil[nx][ny])continue;
		fil[x][y]=fil[nx][ny]=true;
		f(a+1);
		fil[x][y]=fil[nx][ny]=false;
	}
}
int main(){
	int q;
	while(cin>>q,q<5){
		fil=vvi(4,vi(4));
		rep(i,8){
			if(i)cin>>in[i/2][i%2];
			else in[0][0]=q;
		}
		out=0;
		f(0);
		cout<<out<<endl;
	}
}

Measured memory_bytes: 3120
/*** author: yuji9511 ***/
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using lpair = pair<ll, ll>;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i=(m);i<(n);i++)
#define rrep(i,m,n) for(ll i=(m);i>=(n);i--)
#define printa(x,n) for(ll i=0;i<n;i++){cout<<(x[i])<<" \n"[i==n-1];};
void print() {}
template <class H,class... T>
void print(H&& h, T&&... t){cout<<h<<" \n"[sizeof...(t)==0];print(forward<T>(t)...);}

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    ll N,K;
    cin >> N >> K;
    ll A[200010];
    rep(i,0,N) cin >> A[i];
    sort(A, A+N);
    ll zero = 0;
    rep(i,0,N){
        if(A[i] == 0) zero++;
    }
    vector<ll> plus, minus;
    rep(i,0,N){
        if(A[i] > 0) plus.push_back(A[i]);
        else if(A[i] < 0) minus.push_back(A[i]);
    }
    ll zero_cnt = N*(N-1)/2 - (N-zero) * (N-zero-1) / 2;
    ll lv = -1e18+1, rv = 1e18+1;
    ll sz1 = plus.size(), sz2 = minus.size();
    while(rv - lv > 1){
        ll mid = (rv + lv) / 2;
        bool ok = true;
        ll res = 0;
        ll res_tmp = 0;
        rep(i,0,sz1){
            ll v = plus[i];
            if(mid >= 0){
                ll lv1 = i, rv1 = sz1;
                while(rv1 - lv1 > 1){
                    ll mid1 = (lv1 + rv1) / 2;
                    if(v * plus[mid1] <= mid){
                        lv1 = mid1;
                    }else{
                        rv1 = mid1;
                    }
                }
                res += lv1 - i;
            }
            ll lv1 = -1, rv1 = sz2;
            while(rv1 - lv1 > 1){
                ll mid1 = (rv1 + lv1) / 2;
                if(v * minus[mid1] <= mid){
                    lv1 = mid1;
                }else{
                    rv1 = mid1;
                }
            }

            res_tmp += lv1+1;
        }

        rep(i,0,sz2){
            ll v = minus[i];
            if(mid >= 0){
                ll lv1 = i, rv1 = sz2;
                while(rv1 - lv1 > 1){
                    ll mid1 = (lv1 + rv1) / 2;
                    if(v * minus[mid1] <= mid){
                        rv1 = mid1;
                    }else{
                        lv1 = mid1;
                    }
                }
                res += sz2- rv1;
            }
            ll lv1 = -1, rv1 = sz1;
            while(rv1 - lv1 > 1){
                ll mid1 = (rv1 + lv1) / 2;
                if(v * plus[mid1] <= mid){
                    rv1 = mid1;
                }else{
                    lv1 = mid1;
                }
            }
            res_tmp += sz1 - rv1;
        }

        res += res_tmp/2;
        if(mid >= 0) res += zero_cnt;

        if(res >= K){
            ok = true;
        }else{
            ok = false;
        }

        if(ok){
            rv = mid;
        }else{
            lv = mid;
        }
    }
    print(rv);

    

}

Measured memory_bytes: 4084
#include <iostream>
#include <string>
#include <cmath>
#define rep(i, n) for(int i = 0; i < n; i++)
using namespace std;

int main(){
  int n;
  cin >> n;
  int ans = 0;
  int now = 0;
  int prev = -1;
  rep(i, n){
    int h;
    cin >> h;
    if (prev >= h) now++;
    else now = 0;
    ans = max(ans, now);
    prev = h;
  }
  cout << ans << endl;
  
  return 0;
}

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

def count(i,x,y,z):
	if i > N:
		return 0
	c = 1 if x * y * z > 0 else 0
	c += count(i*10+7, x+1, y, z)
	c += count(i*10+5, x, y+1, z)
	c += count(i*10+3, x, y, z+1)
	return c

print(count(0,0,0,0))


Measured memory_bytes: 3060
N,M = map(int,input().split())
dic = {}
 
for _ in range (M):
  p, s = input().split()
  if p not in dic and s == 'AC':
    dic[p] = [1,0]
  elif p not in dic and s == 'WA':
    dic[p] = [0,1]
  elif s == 'AC' and dic[p][0] == 0:
    dic[p][0] += 1
  elif s == 'WA' and dic[p][0] == 0:
    dic[p][1] += 1

right = 0
wrong = 0
 
for item in dic.values():
  right += item[0]
  if item[0]==1:
    wrong += item[1]

print(right, wrong)

Measured memory_bytes: 25288
primes = [i for i in range(55555)]
primes[1] = 0 

for p in primes:
    if p > int(55555**(1/2)): break
    if p == 0: continue
    for non_prime in range(2 * p, 55555, p): primes[non_prime] = 0

    prime = [prime for prime in primes if prime != 0]

cand = set([10*i+1 for i in range(5554)])
prime5 = list(set(prime) & cand)

N = int(input())
ans = []
for i in range(N):
    ans.append(prime5[i])
print(*ans)

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

int main(){
	int c1,c5,c10,c50,c100,c500;
	cin>>c1>>c5>>c10>>c50>>c100>>c500;
	if(c1+c5*5+c10*10+c50*50+c100*100+c500*500>=1000) cout<<1<<endl;
	else cout<<0<<endl;
	return 0;
}


Measured memory_bytes: 3100
#include<iostream>
using namespace std;
#define MAX 500005

int H, A[MAX + 1];

void maxHeap(int i) {
	int l, r, large;
	l = 2 * i;
	r = 2 * i + 1;

	if (l <= H&&A[l] > A[i]) {
		large = l;
	}
	else {
		large = i;
	}
	if (r <= H&&A[r] > A[large]) {
		large = r;
	}
	if (large!=i) {
		swap(A[large], A[i]);
		maxHeap(large);
	}
}

int main()
{
	cin >> H;
	for (int i = 1; i <= H; i++) cin >> A[i];
	for (int i = H / 2; i >= 1; i--) maxHeap(i);
	for (int i = 1; i <= H; i++) {
		cout << " " << A[i];
	}
	cout << endl;
    return 0;
}

Measured memory_bytes: 5056
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<bitset>
#include<vector>
#include<deque>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<cmath>
#include<iomanip>
#include <functional>
using namespace std;
typedef long long ll;
const int mod = 1000000007;
const int INF = 1 << 30;
const double EPS = 1e-10;
//cout << fixed << std::setprecision(9)
//memset(a, 0, sizeof(a));
//--------------------------

int main()
{
	int n, m;
	cin >> n >> m;
	cout << (n - 1) * (m - 1) << endl;
	return 0;
}


Measured memory_bytes: 256
#include <stdio.h>
#include <math.h>
#define M M_PI/3
#define N 500001

typedef struct{
    double x,y;
}Point;
void print(Point p){
    printf("%.10f %.10f\n",p.x,p.y);
}
Point rota(Point p1,Point p2){
    double x=p2.x-p1.x;
    double y=p2.y-p1.y;
    Point p={x*cos(M)-y*sin(M)+p1.x,x*sin(M)+y*cos(M)+p1.y};
    return p;
}
void sen(int n,Point p1,Point p2){
    if(n==0) return;
    Point s={p1.x+(p2.x-p1.x)/3.0,p1.y+(p2.y-p1.y)/3.0};
    Point t={p1.x+(p2.x-p1.x)*2.0/3.0,p1.y+(p2.y-p1.y)*2.0/3.0};
    Point u = rota(s,t);
    sen(n-1,p1,s);
    print(s);
    sen(n-1,s,u);
    print(u);
    sen(n-1,u,t);
    print(t);
    sen(n-1,t,p2);
}
int main()
{
  int n;
  Point p1={0,0};
  Point p2={100,0};
  scanf("%d",&n);
  print(p1);
  if(n>0){
      sen(n,p1,p2);
  }
  print(p2);
  return 0;
}



Measured memory_bytes: 1992
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
using ll = long long;

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

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

    constexpr int M = 2019;
    int p[M] = {};
    int t = 0, d = 1;
    ll r = 0;

    for (int i = n - 1; i >= 0; i--) {
        p[t]++;
        t = ((s[i] - '0') * d + t) % M;
        d = d * 10 % M;
        r += p[t];
    }

    cout << r << endl;

    return 0;
}

Measured memory_bytes: 3752
#include<bits/stdc++.h>
typedef long long ll;
#define dbg          cout<<"Freak"<<endl;
#define dbgg(i)      cout<<i<<endl;
#define N            1e9+7
#define pb           push_back
#define pi           acos(-1)
using namespace std;
ll arr[100005];
ll t;
vector<string>v;
map<string,ll>mp;
map<string,string>np;
int main()
{
    ll a,b,c,d,e,f=0,i,j;
    cin>>a;
    for(i=0;i<a;i++)
    {
        cin>>b;
        if(b%2==0)
        {
            if(b%3==0||b%5==0)
            {

            }
            else f=1;
        }
    }
    if(f==1)cout<<"DENIED"<<endl;
    else cout<<"APPROVED"<<endl;
}




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

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef vector<vll> vvll;
typedef vector<string> vs;
typedef pair<int, int> P;

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()

void YN(bool flg){if(flg) cout << "YES" << endl; else cout << "NO" << endl;}
void Yn(bool flg){if(flg) cout << "Yes" << endl; else cout << "No" << endl;}
void yn(bool flg){if(flg) cout << "yes" << endl; else cout << "no" << endl;}

// int 型の要素を持ち、最も大きい値を取り出す形の priority_queue を定義する場合
priority_queue<int, vector<int>, less<int>> q;

int main()
{
    int n;
    cin >> n;
    vll a(n);
    rep(i, n) cin >> a[i];

    sort(rall(a));

    q.push(a[0]);

    ll ans = 0;
    for(int i = 1; i < n; i++) {
        ans += q.top(); q.pop();
        rep(j, 2) q.push(a[i]);
    }

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


Measured memory_bytes: 5888
#include <iostream>

int main()
{
  int n;
  std::cin >> n;
  int a[200000];
  for (int i=0; i<n; ++i)
  {
    std::cin >> a[i];
  }
  long long sum = 0;
  int saikou = a[0];
  for (int i=1; i<n; ++i)
  {
    if (saikou > a[i])
    {
      sum += saikou - a[i];
    }
    else
    {
      saikou = a[i];
    }
  }
  std::cout << sum;
  return 0;
}

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

int main() {

  int n,l;
  cin >> n >> l;
  string a;
  
  vector<string> s(n);
  for ( int i = 0; i < n; i++){
    cin >> s[i];
  }
  
  sort(s.begin(),s.end());
  
  for ( int i = 0; i < n; i++){
    a+= s[i];
  }
  
  cout << a << endl;
  
}


Measured memory_bytes: 256
import scala.io.StdIn.readLine

object Main {

  def main(args: Array[String]) = {
      val n = readLine().split(" ").map(_.toInt).sorted
      val (a,b,c) = (n(0),n(1),n(2))
      println(a + " " + b + " " + c)
  }
}

Measured memory_bytes: 43672
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define eb emplace_back
typedef long double ld;

int N, A[200005];
map<pair<int, int>, int> mem;

int dp(int n, int k) {
	if (k == 0) return 0;
	if (mem.find(mp(n, k)) != mem.end()) return mem[mp(n, k)];
	if ((N - n + 2) / 2 < k) return -1e17;
	if (n >= N + 1) return (k == 0 ? 0 : -1e17);
	return mem[mp(n, k)] = max(dp(n + 2, k - 1) + A[n], dp(n + 1, k));
}

main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> N;
	for (int i = 1; i <= N; i++) cin >> A[i];
	cout << dp(1, N / 2) << '\n';
}


Measured memory_bytes: 33340
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
#include <bitset>
#include<math.h>
using namespace std;
#define INF 11000000000
#define MOD 1000000007
typedef long long ll;
typedef pair<ll,ll> P;

ll dp[2000][1<<13];
vector<int> V[2100];

int main(){
    int N,M,a[2100],b,c;
    cin>>N>>M;
    for(int i=0;i<2000;i++){
        for(int j=0;j<(1<<13);j++){
            dp[i][j]=INF;
        }
    }
    dp[0][0]=0;

    for(int i=0;i<M;i++){
        cin>>a[i]>>b;
        for(int j=0;j<b;j++){
            cin>>c;
            c--;
            V[i].push_back(c);
        }
    }
    
    for(int i=0;i<M;i++){
        for(int j=0;j<(1<<N);j++){
            if(dp[i][j]==INF) continue;
            int temp=j;
            for(int k=0;k<(int)V[i].size();k++){
                temp|=(1<<V[i][k]);
            }
            dp[i+1][temp]=min(dp[i][j]+a[i],dp[i+1][temp]);
            dp[i+1][j]=min(dp[i][j],dp[i+1][j]);            
        }
    }
    if(dp[M][(1<<N)-1]==INF) cout<<-1<<endl;
    else cout<<dp[M][(1<<N)-1]<<endl;
}


Measured memory_bytes: 128384
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <list>
#include <set>
#include <map>
#include <numeric>
#include <regex>
#include <tuple>
#include<iomanip>
using namespace std;

typedef long long ll;
typedef pair<int, int> P;
#define MOD 1000000007 // 10^9 + 7
#define INF 1000000000 // 10^9
#define LLINF 1LL<<60


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

	ll N; cin >> N;
	cout << N * (N - 1) / 2 << endl;

	return 0;
}

Measured memory_bytes: 256
main = do
  n_ <- getLine
  let 
    n = read $ head $ words n_ :: Int
    cards = foldr (++) [] $ (\la -> \lb -> (map (\a -> map (\b -> (a,b)) lb) la)) ['S','H','C','D'] [1..13]
    output ls
      | length ls == 0  = ""
      | otherwise       = ([fst $ head ls]) ++ " " ++ (show $ snd $ head ls) ++ "\n" ++ (output $ tail ls)
    func cards n = 
      if n > 0 
        then do
          line <- getLine
          let 
            suit = head $ head $ words line :: Char
            rank = read $ head $ tail $ words line :: Integer
            remove cards suit rank
              | suit /= (fst $ head cards)  = (head cards) : (remove (tail cards) suit rank)
              | rank /= (snd $ head cards)  = (head cards) : (remove (tail cards) suit rank)
              | otherwise                   = tail cards
            in
              func (remove cards suit rank) (n-1)
        else 
          putStr $ output cards
    in
      func cards n



Measured memory_bytes: 4088
#include<iostream>
#include<string.h>
#include<ctype.h>
#include<string>
#include<math.h>
#define pi 3.141592653589
#include<iomanip>
using namespace std;
#include<algorithm>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define INF 1e9
#define LINF 1e17
#define ll long long
#define MOD (int)(1e9+7)

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



int main() {

	int n, l, r, ans = 0;

	cin >> n;
	rep(i, 0, n) {
		cin >> l >> r;
		ans += r - l + 1;
	}
	cout << ans << endl;

	return 0;
}

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

#define int long long
using P = pair<int, int>;

struct edge {
    int to;
    int cost;
    edge(int to, int cost) : to(to), cost(cost) { }
};

int V, E, r;

vector<edge> G[100001];
int d[100001];

auto dijkstra(int s) -> void {
    priority_queue<P, vector<P>, greater<P> > que;
    fill(d, d+V, 1e+9);
    d[s] = 0;
    que.push(P(0,s));
    while(!que.empty()) {
        P p = que.top();
        que.pop();
        int v = p.second;
        if(d[v]<p.first) continue;
        for(int i=0; i<G[v].size(); ++i) {
            edge e = G[v][i];
            if(d[e.to]>d[v]+e.cost) {
                d[e.to] = d[v] + e.cost;
                que.push(P(d[e.to],e.to));
            }
        }
    }
}

auto main() -> signed {
    cin >> V >> E >> r;
    int s, t, di;
    for(int i=0; i<E; ++i) {
        cin >> s >> t >> di;
        G[s].push_back(edge(t,di));
    }
    dijkstra(r);
    for(int i=0; i<V; ++i) {
        if(d[i]==1e+9) cout << "INF" << endl;
        else cout << d[i] << endl;
    }
    return 0;
}

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

using namespace std;

typedef long long ll;

const ll M = 1e9 + 7;

ll bin_pow(ll a, ll n) {
	if (n == 0) {
		return 1;
	}
	if (n == 1) {
		return a % M;
	}
	if (n % 2 == 0) {
		ll x = bin_pow(a, n / 2) % M;
		x = x * x;
		x %= M;
		return x;
	} else {
		ll x = bin_pow(a, n - 1) % M;
		x = x * (a % M);
		x %= M;
		return x;
	}
}

ll fact(ll l, ll r) {
	ll res = 1;
	for (ll i = l; i <= r; i++) {
		res *= i;
		res %= M;
	}
	return res;
}

ll get_rev(ll a, ll p) {
	return bin_pow(a, p - 2);
}

int main() {
	#ifdef HOME
	freopen("input.txt", "rt", stdin);
	#endif  //  HOME
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n, a, b;
	cin >> n >> a >> b;
	ll ans = bin_pow(2, n) % M;
	ll x1 = fact(n - a + 1, n);
	ll y1 = fact(1, a);
	ll yy1 = get_rev(y1, M);
	ll p1 = x1 * yy1;
	p1 %= M;
	ll x2 = fact(n - b + 1, n);
	ll y2 = fact(1, b);
	ll yy2 = get_rev(y2, M);
	ll p2 = x2 * yy2;
	p2 %= M;
	ans = ans - p1 - p2 + 2 * M;
	ans %= M;
	cout << ans - 1;
	return 0;
}

Measured memory_bytes: 256
#define	_USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <cctype>
#include <algorithm>
#include <functional>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cfloat>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <string>
#include <set>
#include <complex>
#include <utility>
#include <numeric>
using namespace std;
const int INF=1<<30;

typedef pair<int,int> P;

int main(){
	
	int n;
	while(cin>>n&&n){
		string l;
		cin.ignore();
		map<string,int> W;
		vector< pair<int,string> > S;
		for(int i=0;i<n;i++){
			getline(cin,l);
		if(l[l.size()-1]=='\r'){
			l=l.substr(0,l.size()-1);
		}
		
		stringstream ss(l);
		while(ss >> l){
			W[l]--;
		}
		}
	for( map<string,int>::iterator it= W.begin();it!=W.end();it++){
		S.push_back(make_pair(it->second,it->first));
	}
	char b;
	cin>>b;
	sort(S.begin(),S.end());
	int k=0;
	for(int i=0;i<S.size();i++){
		if(S[i].second[0]==b&&k<5){
			cout<< (k++?" ":"")<<S[i].second;
		}
	}
	if(!k)
		cout<<"NA"<<endl;
	else
		cout<<endl;
	}
	
	
}

Measured memory_bytes: 3204
#include<bits/stdc++.h>
#define it register int
#define ct const int
#define il inline
using namespace std;
typedef long long ll;
#define rll register ll
#define cll const ll
typedef double db;
#define rdb register db
#define cdb const db
#define pb push_back
#define mkp make_pair
#define pl pair<ll,int> 
#define pi pair<int,int> 
namespace io{
	il char nc(){
		static char buf[100000],*p1=buf,*p2=buf;
		return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++; 
	}
	template <class I> 
	il void fr(I &num){
		num=0;register char c=nc();it p=1;
		while(c<'0'||c>'9') c=='-'?p=-1,c=nc():c=nc();
		while(c>='0'&&c<='9') num=num*10+c-'0',c=nc();
		num*=p;
	} 
	template <class I> 
	il I Max(I p,I q){return p>q?p:q;}
	template <class I> 
	il I Min(I p,I q){return p<q?p:q;}
	template <class I> 
	il I A(I x){return x<0?-x:x;}
	template <class I> 
	il void sp(I&p,I&q){I x=p;p=q,q=x;}
	template <class I>
	il void ckMax(I&p,I q){p=(p>q?p:q);}
	template <class I>
	il void ckMin(I&p,I q){p=(p<q?p:q);}
};
using io :: fr;
using io :: nc;
using io :: Max;
using io :: Min;
using io :: A;
using io :: sp;
using io :: ckMax;
using io :: ckMin;
const int N=2000005;
const db Pi=acos(-1);
#define P 200003
int n,a[N],mx,id[N],pw[N],r[N];
struct E{
	db x,y;
	E(){}
	E(cdb a,cdb b){x=a,y=b;}
	E operator + (const E&p)const{return E(x+p.x,y+p.y);}
	E operator - (const E&p)const{return E(x-p.x,y-p.y);}
	E operator * (const E&p)const{return E(x*p.x-y*p.y,x*p.y+y*p.x);}
	E operator / (const db&p)const{return E(x/p,y/p);}
}f[N];
il void fft(E*a,ct isi,ct n){
	it l,i,j,p;register E wn,w,x,y;
	for(i=0;i<n;++i) if(i<r[i]) sp(a[i],a[r[i]]);
	for(l=1;l<n;l<<=1)
		for(i=0,p=l<<1,wn=E(cos(Pi/l),isi*sin(Pi/l));i<n;i+=p)
			for(j=0,w=E(1,0);j<l;++j,w=w*wn)
				x=a[i+j],y=a[l+i+j]*w,a[i+j]=x+y,a[l+i+j]=x-y;
	if(isi<0) for(i=0;i<n;++i) a[i].x/=n;
}
int main(){
	scanf("%d",&n);it i;ct L=P-1,LL=L<<1;
	for(i=pw[0]=1;i<L;++i) pw[i]=pw[i-1]<<1,pw[i]=(pw[i]>=P?pw[i]-P:pw[i]),id[pw[i]]=i;
	for(i=1;i<=n;++i) scanf("%d",&a[i]),a[i]?f[id[a[i]]].x+=1,mx=(a[i]>mx?a[i]:mx):0;
	it len=1,sz=-1;while(len<=LL) len<<=1,++sz;
	for(i=1;i<len;++i) r[i]=(r[i>>1]>>1)|((i&1)<<sz);
	fft(f,1,len);for(i=0;i<len;++i) f[i]=f[i]*f[i];fft(f,-1,len);
	for(i=1;i<=n;++i) a[i]?f[id[a[i]]<<1].x-=1,0:0;
	rll ans=0;for(i=0;i<len;++i) ans+=(ll) (f[i].x/2+1e-1)*pw[i%L];printf("%lld",ans);
	return 0;
}


Measured memory_bytes: 16692
package main

import (
	"fmt"
	"os"
)

func main() {
	var a, b, c, d, total, input int
	var outb, outc, outd string
	fmt.Scanf("%d/n", &input)

	a = input / 1000
	input = input % 1000
	b = input / 100
	input = input % 100
	c = input / 10
	input = input % 10
	d = input

	for ib := -1; ib <= 1; ib += 2 {
		for ic := -1; ic <= 1; ic += 2 {
			for id := -1; id <= 1; id += 2 {
				total = a + b*ib + c*ic + d*id
				if total == 7 {
					if ib == -1 {
						outb = "-"
					} else {
						outb = "+"
					}
					if ic == -1 {
						outc = "-"
					} else {
						outc = "+"
					}
					if id == -1 {
						outd = "-"
					} else {
						outd = "+"
					}
					fmt.Printf("%d%s%d%s%d%s%d=7", a, outb, b, outc, c, outd, d)
					os.Exit(0)
				}
			}
		}
	}

}


Measured memory_bytes: 1876