akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
bool ok(int k, vector<int> &D) {
  while(k > 0) {
    int d = k % 10;
    if (D[d]) return false;
    k /= 10;
  }
  return true;
}
 
int main() {
  int N, K;
  cin >> N >> K;
  vector<int> D(10);
  for(int i = 0; i < K; i++) {
    int d; cin >> d;
    D[d] = 1;
  }
  for(int i = N; i <= 10 * N; i++) {
    if (ok(i, D)) {
      cout << i << endl;
      break;
    }
  }
  return 0;
}

Measured memory_bytes: 256
import java.util.*;

public class Main{


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long m = sc.nextLong();
        long[] a = new long[n];
        for (int i = 0; i < n; i++) a[i] = sc.nextLong();
        Arrays.sort(a);

        long left = 0;
        long right = a[n-1]*2+1;
        while (left<right){
            long mid = (left+right)/2;
            long c = numberOfHandshake(mid, a);
            if (c<=m){
                right = mid;
            }else {
                left = mid+1;
            }
        }
        long c = numberOfHandshake(left, a);
        long h = totalHappiness(left, a);
        if (c<m){
            h += (left-1)*(m-c);
        }
        System.out.println(h);
    }


    public static long numberOfHandshake(long x, long[] a){
        int n = a.length;
        long ret = 0;
        for (int i=0; i<n; i++){
            ret += n - lowerbound(x-a[i], a);
        }
        return ret;
    }

    public static long totalHappiness(long x, long[] a){
        int n = a.length;
        long[] sum = new long[n+1];
        for (int i=0; i<n; i++){
            sum[i+1] = sum[i] + a[i];
        }
        long ret = 0;
        for (int i=0; i<n; i++){
            int idx = lowerbound(x-a[i], a);
            ret += sum[n]-sum[idx]+(n-idx)*a[i];
        }
        return ret;
    }


    public static int lowerbound(long value, long[] arr){
        int n = arr.length;
        int left = 0;
        int right = arr.length;
        if (arr[n-1]<value){
            return n;
        }
        if (arr[0]>=value){
            return 0;
        }
        while (left<right){
            int mid = (left+right)/2;
            if (arr[mid]<value){
                left = mid+1;
            }else {
                right = mid;
            }
        }
        return left;
    }
}

Measured memory_bytes: 60964
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <queue>
#include <iomanip>
#include <set>
#define MOD 1000000007
#define mkp make_pair
typedef long long ll;
using namespace std;

const ll INF=1e9;

int main(){
  ll S;
  cin>>S;

  ll a,b,c,d;
  a=INF;
  b=(S+INF-1)/INF;
  c=abs(S-a*b);
  d=1;

  cout<<0<<" "<<0<<" "<<a<<" "<<d<<" "<<c<<" "<<b<<endl;

  return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int main(){
    string str;
    getline(cin, str);
    long long int sum = 0;
    for(int i = 0; i < str.length(); i++){
        sum += str[i] - '0';
    }
    if(sum % 9 == 0) cout << "Yes";
    else cout << "No";
}

Measured memory_bytes: 3744
#include <cstdlib>
#include <iostream> 
#include <vector>
#include <algorithm>   

using namespace std;

int main(void){
	int d;
	int n,m;
	int a,b;
	long long int ans=0;
	while(1){
		cin >> d;
		if(d==0)break;
		ans=0;
		vector<int> data;
		data.push_back(0);
		cin >> n;
		cin >> m;
		for(a=0;a<n-1;a++){
			scanf("%d",&b);
			data.push_back(b);
		}
		data.push_back(d);
		sort(data.begin(),data.end());
		for(a=0;a<m;a++){
			cin >> b; 
			int w=abs(b-*(lower_bound(data.begin(),data.end(),b)-1)); 
			w=min(w,abs(b-*lower_bound(data.begin(),data.end(),b)));
			ans+=w;
		}
		cout << ans << endl;
	}
	return 0;
}

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

int main() {

  int n;
  cin >> n;
  int a[n];

  for(int i=0;i<n;i++)
    cin >> a[i];
  
  for(int j=0;j<n-1;j++)
    cout << a[j] << ' ';
  cout << a[n-1] << endl;
  
  for(int i=1;i<n;i++){
    int v = a[i],j;
    for(j=i-1;j>=0&&a[j]>v;j--)
      a[j+1] = a[j];
    
    a[j+1]=v;
    
    for(int j=0;j<n-1;j++)
      cout << a[j] << ' ';
    cout << a[n-1] << endl;
  }
}

Measured memory_bytes: 1160
#include <bits/stdc++.h>
#define LOOP(n) for (int _i = 0; _i < (n); _i++)
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define FOR(i, r, n) for (int i = (r); i < (n); ++i)
#define ALL(obj) begin(obj), end(obj)
using namespace std;
using ll = long long;
using ull = unsigned long long;

const int INF = 2100100100;
const int MOD = 1e9 + 7;

// 多次元 vector 生成
template <class T>
vector<T> make_vec(size_t a) {
    return vector<T>(a);
}
template <class T, class... Ts>
auto make_vec(size_t a, Ts... ts) {
    return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}
template <class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return 1;
    }
    return 0;
}

int main() {
    // cin.tie(0);
    // ios::sync_with_stdio(false);
    int N, K;
    cin >> N >> K;
    vector<int> A(N);
    REP(i, N) { cin >> A.at(i); }

    cout << (N - K + K - 2) / (K - 1) + 1 << endl;
    return 0;
}


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

#define MAX 500001
#define SEN 1000000000
typedef long long llong;


llong A[MAX];
llong Left[MAX/2+1], Right[MAX/2+1];
int cnt = 0;
void merge(llong A[], int left, int mid, int right){
	int n1 = mid - left;
	int n2 = right - mid;
	for(int i=0; i<n1; i++) Left[i] = A[left+i];
	for(int i=0; i<n2; i++) Right[i] = A[mid+i];
	Left[n1] = SEN; Right[n2] = SEN;

	int i,j;
	i=j=0;
	for(int k=left; k<right; k++){
		cnt++;
		if(Left[i]<=Right[j]){
			A[k] = Left[i++];
		}else{
			A[k] = Right[j++];
		}
	}
}

void mergesort(llong A[], int left, int right){
	if(left+1<right){
		int mid = (left+right) / 2;
		mergesort(A, left, mid);
		mergesort(A, mid, right);
		merge(A, left, mid, right);
	}
}

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

	mergesort(A, 0, n);

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


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

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

    int answer = 100000000;

    for(int j=0; j<100; j++)
    {
        int sum = 0;

        for(int k=0; k<N; k++)
        {
            sum = sum + (j-X[k])*(j-X[k]);
        }

        if(sum < answer)
        {
            answer = sum;
        }
    }

    cout << answer;

    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define For(i,x,y) for (register int i=(x);i<=(y);i++)
#define FOR(i,x,y) for (register int i=(x);i<(y);i++)
#define Dow(i,x,y) for (register int i=(x);i>=(y);i--)
#define Debug(v) for (auto i:v) printf("%lld ",i);puts("")
#define mp make_pair
#define fi first
#define se second
#define pb push_back
#define ep emplace_back
#define siz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define fil(a,b) memset((a),(b),sizeof(a))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pa;
typedef pair<ll,ll> PA;
typedef vector<int> poly;
inline ll read(){
    ll x=0,f=1;char c=getchar();
    while ((c<'0'||c>'9')&&(c!='-')) c=getchar();
    if (c=='-') f=-1,c=getchar();
    while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
    return x*f;
}

const int N = 1e5+10, mod = 998244353;
int n,mx,a[N],cnt[N];

inline int power(int a,int b){
	int ret=1;
	for (;b;b>>=1,a=1ll*a*a%mod) if (b&1) ret=1ll*ret*a%mod;
	return ret;
}

int main(){
	n=read();
	For(i,1,n) cnt[a[i]=read()]++,mx=max(mx,a[i]);
	if (a[1]||cnt[0]>1) return puts("0"),0;
	int ans=1;
	For(i,1,mx) ans=1ll*ans*power(cnt[i-1],cnt[i])%mod;
	printf("%d\n",ans);
}

Measured memory_bytes: 4372
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Main {
	public void exec() throws IOException {
		Scanner input = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);
		int a = input.nextInt();
		int b = input.nextInt();
		out.printf("%d %d %.5f", a/b,a%b,(double)a/b);
		out.flush();
		input.close();
	}

	public static void main(String[] args) throws IOException {
		new Main().exec();
	}
}

Measured memory_bytes: 26560
#include<bits/stdc++.h>
using ll = long long;
#define REP(i,n) for(ll i=0;i<ll(n);i++)
#define FOR(i,a,b) for(ll i=a;i<=ll(b);i++)
#define ALL(x) x.begin(),x.end()

#define INF (ll)1e9 //10^9:∞
#define LLINF (ll)1e12
#define MOD (ll)(1e9+7) //10^9+7:合同式の法
#define PI 3.141592653589
#define PB push_back
#define F first
#define S second
#define __MAGIC__ ios::sync_with_stdio(false);cin.tie(nullptr);

#define YESNO(T) if(T){cout<<"YES"<<endl;}else{cout<<"NO"<<endl;}
#define yesno(T) if(T){cout<<"yes"<<endl;}else{cout<<"no"<<endl;}
#define YesNo(T) if(T){cout<<"Yes"<<endl;}else{cout<<"No"<<endl;}

#define Graph vector<vector<int>>
#define PII pair<int,int>
#define VI vector<int>
#define VVI vector<vector<int>>
#define VPII vector<pair<int,int>>

#define DDD fixed<<setprecision(10)
#define endl "\n"

using namespace std;
/*..................DEFINE GLOBAL VARIABLES...................*/


/*.....................DEFINE FUNCTIONS ......................*/



/*.........................kemkemG0...........................*/
signed main() {
	__MAGIC__


	int N, X, Y;
	cin >> N >> X >> Y;
	X--; Y--;

	Graph G(N);

	REP(i, N - 1) {	
		G.at(i).emplace_back(i + 1);
		G.at(i+1).emplace_back(i);
	}
	G.at(X).emplace_back(Y);
	G.at(Y).emplace_back(X);

	VI ans(N, 0);

	queue<int> q;

	FOR(i, 0, N - 2) {
		VI dist(N, INF);

		dist[i] = 0;
		q.push(i);

		while (!q.empty()) {
			int now = q.front(); q.pop();
			REP(j,G[now].size()) {
				if (dist[G[now][j]] == INF   ) {
					dist[G[now][j]] = dist[now] + 1;

					if(i<G[now][j])ans[dist[G[now][j]]]++;

					q.push(G[now][j]);
				}
			}
		}

	}

	FOR(i, 1, N - 1)cout << ans[i] << endl;




	return 0;
}


Measured memory_bytes: 3752
#include <stdio.h>

int main(void) {
	int x, y, i;
	for (i = 0; i<3000; i++){
	scanf("%d %d", &x, &y);
	if ( x == 0 && y == 0 ) break; 	
	if(x < y){
	printf("%d %d\n", x, y);
	}else{
	printf("%d %d\n", y, x);
}
 
}
	return 0;
}


Measured memory_bytes: 2052
#include<iostream>
#include<cstdio>
using namespace std;
int N;
int A[100000];
int B[100000];
int now=0;
int main()
{
	while(true){
		now=0;
		scanf("%d",&N);
		if(N==0)break;
		int col;
		scanf("%d",&col);
		A[0]=col;B[0]=1;
		for(int i=1;i<N;i++){
			scanf("%d",&col);
			if(i&1){
				if(A[now]==col)B[now]++;
				else{
					if(now==0){
						A[now]=col;B[now]++;
					}
					else{
						B[now-1]+=(B[now]+1);
						A[now]=0;B[now]=0;
						now--;
					}
				}
			}
			else{
				if(A[now]==col)B[now]++;
				else{
					now++;A[now]=col;B[now]=1;
				}
			}
		}
		int ans=0;
		for(int i=0;i<=now;i++){
			if(A[i]==0)ans+=B[i];
			A[i]=0;B[i]=0;
		}
		printf("%d\n",ans);
	}
}

Measured memory_bytes: 1196
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

fn extgcd(a: i64, b: i64, x: &mut i64, y: &mut i64) -> i64 {
    let mut d = a;
    if b == 0 {
        *x = 1;
        *y = 0;
    } else {
        d = extgcd(b, a % b, y, x);
        *y -= (a / b) * (*x);
    }
    return d;
}

fn mod_inverse(a: i64, m: i64) -> i64 {
    let mut x: i64 = 0;
    let mut y: i64 = 0;
    extgcd(a, m, &mut x, &mut y);
    (m + x % m) % m
}

fn main() {
    let n: usize = read();
    let a = read_vec::<i64>();
    let big_int = 1000_000_000 + 7;
    let mut mod_invs = vec![0i64; n + 1];
    mod_invs[1] = 1;
    for i in 2..n + 1 {
        mod_invs[i] = mod_inverse(i as i64, big_int);
    }

    let mod_inv_sums: Vec<i64> = (1..n+1).map(|x| mod_inverse(x as i64, big_int))
                                         .scan(0, |ac, x| {*ac = (*ac + x) % big_int; Some(*ac)})
                                         .collect();
    // println!("{:?}", mod_inv_sums);
    let mut ans = 0;

    for i in 0..n {
        ans += a[i] * (mod_inv_sums[i] + mod_inv_sums[n - i - 1] - 1);
        ans %= big_int;
    }
    // println!("{:?}", ans);
    for i in 1..n + 1 {
        ans *= i as i64;
        ans %= big_int;
    }
    println!("{:?}", ans);
}


Measured memory_bytes: 9464
#include<iostream>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
#define REP(i,b,n) for(int i=b;i<n;i++)
#define rep(i,n)   REP(i,0,n)
#define ALL(c)   (c).begin(),(c).end()
#define pb push_back
#define mp make_pair

typedef pair<int,int> pii;

const int N =200;
const int inf = (1<<20);

int cost[2][N];
int in[2][N];

int getheight(int n,int ind,int i){
  if (in[ind][i] == 1){
    int hi=i;
    REP(j,i,n){
      if (in[ind][j] != 1)break;
      hi=j;
    }
    return hi;
  }else if (in[ind][i] == 2){
    int lo=i;
    for(int j=i;j>=0;j--){
      lo=j;
      if (in[ind][j] != 2)break;
    }
    return lo;
  }
  return i;
}

class st{
public:
  int p;
  int h;
  int cost;
};

void bfs(int n){
  rep(i,2)rep(j,n)cost[i][j]=inf;
  queue<st> Q;
  int a=getheight(n,0,0),b=getheight(n,1,0);
  Q.push((st){0,a,0});
  Q.push((st){1,b,0});
  cost[0][a]=0;
  cost[1][b]=0;
  while(!Q.empty()){
    st now = Q.front();Q.pop();
    if (now.h == n-1){
      cout << now.cost << endl;
      return;
    }

    rep(i,3){
      if (now.h+i == n)break;
      int nextp=1-now.p,nexth=getheight(n,1-now.p,now.h+i);

      if (cost[nextp][nexth] == inf){
	cost[nextp][nexth]=now.cost+1;
	Q.push((st){nextp,nexth,cost[nextp][nexth]});
      }
    }
  }
  cout << "NA" << endl;
}

main(){
  int n;
  while(cin>>n && n){
    rep(i,2){
      rep(j,n){
	cin>>in[i][j];
      }
    }
    bfs(n);
  }
}

Measured memory_bytes: 0
use std::collections::*;

fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let mut s = sc.chars();
    s.reverse();
    let mut sub: Vec<i64> = vec![0; s.len() + 1];
    let m: i64 = 2019;
    let mut pow: i64 = 1;
    for i in 0..s.len() {
        sub[i + 1] = (s[i].to_digit(10).unwrap() as i64 * pow + sub[i]) % m;
        pow = (pow * 10) % m;
    }
    let mut count: BTreeMap<i64, i64> = BTreeMap::new();
    let mut ans: i64 = 0;
    for e in sub.iter() {
        let rf = count.entry(*e).or_insert(0);
        ans += *rf;
        *rf += 1;
    }
    println!("{}", ans);
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: ToString>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.to_string().as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}

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

k = 0
cleared = True
if abs(b-a) % 2 == 0:
    if a < b:
        k = a + abs(b-a)//2
    else:
        k = b + abs(b-a)//2
else:
    cleared = False

if cleared:
    print(k)
else:
    print('IMPOSSIBLE')

Measured memory_bytes: 38384
package main

import (
	"fmt"
)

func main() {
	var k int
	fmt.Scan(&k)
	var sum int
	for a := 1; a <= k; a++ {
		for b := 1; b <= k; b++ {
			for c := 1; c <= k; c++ {
				sum += gcd(gcd(a, b), c)
			}
		}
	}
	fmt.Println(sum)
}

func gcd(a, b int) int {
	if a < b {
		a, b = b, a
	}
	r := a % b
	for r != 0 {
		a = b
		b = r
		r = a % b
	}
	return b
}


Measured memory_bytes: 1776
from collections import Counter
n,p=map(int,input().split())
l=[]
while p%2==0:
    p=p//2
    l.append(2)
while 1:
    k=p
    for i in range(3,int(p**0.5)+1,2):
        if p%i==0:
            l.append(i)
            p=p//i
            break
    if k==p:
        l.append(p)
        break
    elif p==1:break
lc=Counter(l).most_common()
a=1
for i in lc:a*=i[0]**(i[1]//n)
print(a)

Measured memory_bytes: 3316
(defun poison (a b c)
  (declare (optimize (speed 3) (safety 0) (compilation-speed 3) (debug 0)))
  (declare (fixnum a b c))
  (write (if (> (+ a b 1) c) (+ b c) (+ a b b 1)))
  )
(poison (read) (read) (read))

Measured memory_bytes: 11108
import bisect
from collections import defaultdict
n,m = map(int,input().split())
py = [list(map(int,input().split())) for i in range(m)]
py_sorted = sorted(py)
D = defaultdict(int)
num_arr = []
flag = 0

for a in py_sorted:
  if flag == 0:
    flag = 1
    num_arr.append(a[1])
    a_old = a
    continue
  if a[0] == a_old[0]:
    num_arr.append(a[1])
  else:
    for i,j in enumerate(num_arr):
      D[j] = i+1
    num_arr = []
    num_arr.append(a[1])
  a_old = a

for i,j in enumerate(num_arr):
  D[j] = i+1

for a in py:
  print("%06d%06d"%(a[0],D[a[1]]))

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

#define endl '\n'

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

const ll oo = 0x3f3f3f3f3f3f3f3f;

struct monotonic_queue
{
	deque<pii> dq;

	void insert(int p, ll v)
	{
		while(!dq.empty() && dq.back().second <= v)
			dq.pop_back();
		dq.push_back({p, v});
	}

	void erase(int p)
	{
		while(!dq.empty() && dq.front().first < p)
			dq.pop_front();
	}

	ll max() {return dq.empty() ? -oo : dq.front().second; }
};

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

	int n, w;
	cin >> n >> w;

	ll vi;
	vector<ll> best(w + 1);
	for(int i = 0, wi, ci; i < n; ++i)
	{
		cin >> vi >> wi >> ci;
		vector<monotonic_queue> mq(wi);

		int disp = wi * ci;
		for(int j = 0, curk = 0; j <= w; ++j, curk = j % wi)
		{
			ll nv = j / wi * vi;

			mq[curk].erase(j - disp);
			ll good = max(best[j], mq[curk].max() + nv);
			mq[curk].insert(j, best[j] - nv);
			best[j] = good;
		}
	}

	cout << *max_element(best.begin(), best.end()) << endl;

    return 0;
}


Measured memory_bytes: 3548
import java.util.Scanner;

/**
 * Created by Reopard on 2014/07/06.
 */
public class Main{
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args){
        int N, M[][], K[], answer, count;
        while((N = sc.nextInt()) != 0){
            answer = -1;
            M = new int[N][];
            for(int i = 0; i < N; i++){
                M[i] = new int[sc.nextInt()];
                for(int j = 0; j < M[i].length; j++) M[i][j] = sc.nextInt();
            }
            K = new int[sc.nextInt()];
            for(int i = 0; i < K.length; i++) K[i] = sc.nextInt();

            for(int i = 0; i < N; i++){
                count = 0;
                M_search:
                for(int j = 0; j < M[i].length; j++){
                    for(int k: K){
                        if(M[i][j] == k){
                            count++;
                            continue M_search;
                        }
                    }
                }
                if(count == K.length){
                    if(answer != -1){
                        answer = -1;
                        break;
                    }else answer = i + 1;
                }
            }
            System.out.println(answer);
        }
    }
}

Measured memory_bytes: 67008
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#define ll long long
using namespace std;
const  ll mod=998244353;
ll qp(ll a,ll k)
{
	ll ans=1;
	a%=mod;
	while(k)
	{
		if(k%2)
			ans=(ans*a)%mod;
		a=(a*a)%mod;
		k/=2;
	}
	return ans;
}
int main()
{
    int n;
    scanf("%d",&n);
    int a[100005],i;
    int b[100005],flag=1;
    memset(b,0,sizeof(b));
    for(i=0; i<n; i++)
        scanf("%d",&a[i]),b[a[i]]++;
    if(a[0]!=0)
        printf("0\n");
    else
    {
        ll ans=1;
        int t;
        for(i=n-1;b[i]==0;i--);
        t=i;
        if(b[0]==1)
        {
            for(i=2; i<=t; i++)
            {
                if(b[i]==0)
                {
                    flag=0;
                    break;
                }
                ans=(ans*(ll)qp(b[i-1],b[i]))%mod;
            }
            if(flag==1)
            	printf("%lld\n",ans%mod);
            else
            	printf("0\n");
        }
        else
            printf("0\n");
    }

    return 0;
}


Measured memory_bytes: 1656
// B - Mix Juice
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n, k;
    cin >> n >> k;
    vector <int> p(n);
    for(int i=0; i<n; i++) cin >> p[i];
    sort(p.begin(), p.end());
    int ans = 0;
    for(int i=0; i<k; i++) ans += p[i];
    cout << ans << endl;
}

Measured memory_bytes: 3644
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <bitset>
#include <iomanip>
using namespace std;


void SelectionSort(vector<string> Array, int N)
{
  	bool isStable=true;
  	for(int i = 0; i< N;i++)
    {
      int min_idx = i;
      bool isSame = false;
      int same_idx;
      for(int j=i+1;j<N;j++)
      {
        if(Array[j][1] - '0' == Array[min_idx][1] - '0') 
        {
          isSame=true;
          same_idx = j;
        }
        if(Array[j][1] - '0' < Array[min_idx][1] - '0')
        {
          min_idx = j;
        }
      }
      if(isSame && same_idx < min_idx) isStable = false;
      string tmp = Array[i];
      Array[i] = Array[min_idx];
      Array[min_idx] = tmp;
    }
	for(int i=0;i<N;i++)
    {
      cout << Array[i] << endl;
    }
  	cout << Array[N-1] << endl;
}

int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	double N, K;
	cin >> N >> K;
  	//string S;
  	//cin >> S;	
  	/*
    vector<string> Array(N);
  	int idx = 0;
  	while(cin >> Array[idx]) idx++;
    */
  	double win_rate = 0;
  	double coin = 0.5;
  	for(int i=1;i<=N;i++)
    {
      double v=i;
      double rate=1.0;
      while(v <= K-1)
      {
		v*=2;
        rate*=2;
      }
      cerr << 1/rate << endl;
      win_rate += 1.0/rate;
    }
  	cout << fixed << setprecision(10) << win_rate / N << endl;
  	return 0;
}


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

#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("avx,avx2,fma")

//wierd debugging stuff
#define sim template < class c
#define ris return * this
#define dor > debug & operator <<
#define eni(x) sim > typename \
  enable_if<sizeof dud<c>(0) x 1, debug&>::type operator<<(c i) {
sim > struct rge { c b, e; };
sim > rge<c> range(c i, c j) { return rge<c>{i, j}; }
sim > auto dud(c* x) -> decltype(cerr << *x, 0);
sim > char dud(...);
struct debug {
#ifdef LOCAL
~debug() { cerr << "\n" ; }
eni(!=) cerr << boolalpha << i; ris; }
eni(==) ris << range(begin(i), end(i)); }
sim, class b dor(pair < b, c > d) {
  ris << "(" << d.first << ", " << d.second << ")";
}
sim dor(rge<c> d) {
  *this << "[";
  for (auto it = d.b; it != d.e; ++it)
    *this << ", " + 2 * (it == d.b) << *it;
  ris << "]";
}
#else
sim dor(const c&) { ris; }
#endif
};
#define imie(...) " [" << #__VA_ARGS__ ": " << (__VA_ARGS__) << "] "
//end of weird debugging stuff
typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ll> vll;
typedef vector<vector<int>> vvi;
#define all(c) (c).begin(), (c).end()
#define sz(x) (int)(x).size()
 
#define F_OR(i, a, b, s) for (int i = (a); ((s) > 0 ? i < (b) : i > (b)); i += (s))
#define F_OR1(e) F_OR(i, 0, e, 1)
#define F_OR2(i, e) F_OR(i, 0, e, 1)
#define F_OR3(i, b, e) F_OR(i, b, e, 1)
#define F_OR4(i, b, e, s) F_OR(i, b, e, s)
#define GET5(a, b, c, d, e, ...) e
#define F_ORC(...) GET5(__VA_ARGS__, F_OR4, F_OR3, F_OR2, F_OR1)
#define fo(...) F_ORC(__VA_ARGS__)(__VA_ARGS__)
#define foe(i,x) for(auto& i: x)
#define ar array
#define pb push_back
#define vt vector
#define F first
#define S second

template<class T> bool umin(T& a,const T& b){return b<a?a=b,1:0;}
template<class T> bool umax(T& a,const T& b){return b>a?a=b,1:0;}

template<class A> void read(vt<A>& v);
template<class A, size_t S> void read(ar<A, S>& a);
template<class T> void read(T& x) {cin>>x;}
void read(double& d) {string t;read(t);	d=stod(t);}
void read(long double& d) {	string t;read(t);d=stold(t);}
template<class H, class... T> void read(H& h, T&... t) {read(h);read(t...);}
template<class A> void read(vt<A>& x) {	foe(a, x)read(a);}

// no change 
const ll MOD = 1e9+7;  
const int mx = 2e5;
int n,W;
void Titan(){
	read(n,W);

	vt<ar<int,2> > A(n+1);
	fo(i,1,n+1)cin >> A[i][0] >> A[i][1];
	
	vt<vll> dp(n+1,vll(W+1));
	
	fo(i,1,n+1){
		for(int j = 1;j <= W;j++){
			if(j - A[i][0] >=0){
				//assert(j ==3 && i == 2);
				dp[i][j] = max(dp[i-1][j] , (dp[i-1][j-A[i][0]]  + 0ll+ A[i][1])) ;
			}else{
				dp[i][j] = dp[i-1][j];
			}
		}
	}

	cout << dp[n][W];

}

int main() {
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	int T = 1;
	//cin >> T;		//cmt if one test case
    fo(T--){
		//cout << "Case #" << i+1 << ": " ;
		Titan();
	}
}
/*///////////////////////////////////////////////////////////
Important Notes : 
* check long long 
* check base cases
* do not loose Hope
* if case fails on 2nd test case maybe some cases are missing check them
* do not sit idle
* try to do it using pen/paper.
*/


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

using namespace std;
using ll = long long int;
constexpr ll M = 1e9 + 7;
inline ll sum_1(const ll n) { return ((n * (n + 1)) / 2) % M; }
inline ll sum_2(const ll n) { return ((n * (n + 1) * (2 * n + 1)) / 6) % M; }
inline ll sum_3(const ll n) { return (((n * (n + 1)) / 2) % M * ((n * (n + 1)) / 2) % M) % M; }
inline ll sum_1(const ll i, const ll j) { return (sum_1(j) - sum_1(i - 1) + M) % M; }
inline ll sum_2(const ll i, const ll j) { return (sum_2(j) - sum_2(i - 1) + M) % M; }
inline ll sum_3(const ll i, const ll j) { return (sum_3(j) - sum_3(i - 1) + M) % M; }

void solve() {
    int k;
    cin >> k;
    ll ans = 0;
    for (int a = 1; a <= k; ++a) {
        for (int b = 1; b <= k; ++b) {
            for (int c = 1; c <= k; ++c) {
                ans += gcd(a,gcd(b,c));
            }
        }
    }
    cout << ans << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    #ifndef ONLINE_JUDGE
        freopen("in.in", "r", stdin);
        freopen("out.out", "w", stdout);
    #endif

    solve();

    return 0;
}

Measured memory_bytes: 3600
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"math/bits"
	"os"
	// "strconv"
	// "strings"
)

//  長い入力を読む
func ReadLongLines(times int) ([]string, error) {
	result := make([]string, times)
	reader := bufio.NewReader(os.Stdin)
	buffer := bytes.NewBuffer(make([]byte, 0))
	readBytes := int64(2)
	for i := 0; i < times; i++ {
		for {
			readBuf, isPrefix, err := reader.ReadLine()
			// fmt.Printf("Reader.Read: %d\n", len(readBuf))
			readBytes += int64(len(readBuf) + 1)
			if err != nil {
				if err == io.EOF {
					fmt.Println("EOF")
					break
				} else {
					return result, err
				}
			}
			_, err = buffer.Write(readBuf)
			if err != nil {
				return result, err
			}
			// end of line
			if !isPrefix {
				result[i] = buffer.String()
				buffer.Reset()
				// reader = bufio.NewReader(os.Stdin)
				break
			}
		}
	}
	// 先読みしてしまうようなので、戻しておく
	os.Stdin.Seek(-int64(reader.Buffered()), os.SEEK_CUR)
	return result, nil
}

// 出力 for 競プロ
type Console struct {
	writer *bufio.Writer
}

func NewConsole() Console {
	return Console{bufio.NewWriter(os.Stdout)}
}
func (this *Console) Printf(format string, a ...interface{}) {
	fmt.Fprintf(this.writer, format, a...)
}
func (this *Console) Println(s string) {
	fmt.Fprintln(this.writer, s)
}
func (this *Console) Close() {
	this.Flush()
}
func (this Console) Flush() {
	this.writer.Flush()
}

func PrintList(list []int) {
	con := NewConsole()
	defer con.Flush()
	for i := range list {
		if i == 0 {
			con.Printf("%d", list[i])
		} else {
			con.Printf(" %d", list[i])
		}
	}
	con.Println("")
}

func main() {
	con := NewConsole()
	defer con.Flush()

	var n int
	fmt.Scanf("%d", &n)

	var k int
	fmt.Scanf("%d", &k)

	max := uint32(1)
	for i := 0; i < n; i++ {
		max = max * 2
	}
	max = max - 1


	for i := uint32(0); i <= max; i++ {
		if bits.OnesCount32(i) != k {
			continue
		}
		con.Printf("%d:", i)
		begin := bits.TrailingZeros32(i)
		end := bits.LeadingZeros32(i)
		for j := begin; j < 32-end; j++ {
			//fmt.Printf("%d & 1<<%d (%d)\n",i, j, (i & (1 << uint32(j))))
			if 0 < (i & (1 << uint32(j))) {
				con.Printf(" %d", j)
			}
		}
		con.Println("")
	}

}



Measured memory_bytes: 4920
N, M = list(map(int, input().split()))
wa = [0]*N
solved = [False]*N
for _ in range(M):
    p, S = input().split()
    p = int(p)-1
    if S=='WA' and not solved[p]:
        wa[p]+=1
    if S=='AC':
        solved[p] = True

ans1 = 0
ans2 = 0
for w, s in zip(wa, solved):
    if s:
        ans1 += 1
        ans2 += w

print(ans1, ans2)

Measured memory_bytes: 4724
X, Y = map(int, input().split())

ans = 0
if X == 1:
    ans += 300000
if X == 2:
    ans += 200000
if X == 3:
    ans += 100000
if Y == 1:
    ans += 300000
if Y == 2:
    ans += 200000
if Y == 3:
    ans += 100000
if X == 1 and Y == 1:
    ans += 400000
print(ans)

Measured memory_bytes: 38384
class DoublyLinkedList

	def initialize
		@guard = Entry.new(nil, nil, nil)
		@guard.prev = @guard
		@guard.succ = @guard
	end

	def insert(value)
		new_entry = Entry.new(value, @guard, @guard.succ)
		@guard.succ.prev = new_entry
		@guard.succ = new_entry
	end

	def delete(value)
		entry = @guard.succ
		entry = entry.succ while entry.value && entry.value != value
		deleteEntry(entry) if entry.value
	end

	def deleteFirst
		deleteEntry(@guard.succ) if @guard.succ.value
	end

	def deleteLast
		deleteEntry(@guard.prev) if @guard.prev.value
	end

	def display
		entry = @guard.succ

		printf "#{entry.value}"
		entry = entry.succ

		while entry.value
			printf " #{entry.value}"
			entry = entry.succ
		end
		printf "\n"
	end

	private
	def deleteEntry(entry)
		entry.succ.prev = entry.prev
		entry.prev.succ = entry.succ
	end

	class Entry
		attr_accessor :value, :prev, :succ

		def initialize(value, prev, succ)
			@value = value
			@prev  = prev
			@succ  = succ
		end

	end

end

list = DoublyLinkedList.new
n = STDIN.gets.split[0].to_i
n.times do
	method_name, param = STDIN.gets.split
	if list.respond_to?(method_name)
		if method_name == "insert" || method_name == "delete"
			list.send(method_name, param)
		else
			list.send(method_name)
		end
	end
end
list.display

Measured memory_bytes: 479000
def int_raw():
    return int(input())

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

def ints_raw():
    return list(map(int, ss_raw()))

INF = 1<<29

N = int_raw()
As =[]
for _ in range(N):
    As.append(int_raw())
SUM = sum(As)

DIV = 998244353

ALL = 1
for _ in range(N):
    ALL = (ALL*3)%DIV

def main():
    dp1 = [0]*(SUM+1)
    dp3 = [0]*(SUM+1)
    dp1[0]=1
    dp3[0]=1
    
    for n in range(N):
        a = As[n]
        dp1 = [(dp1[s]+(dp1[s-a] if s>=a else 0))%DIV for s in range(SUM+1)]
        dp3 = [(dp3[s]*2 + (dp3[s-a] if s>=a else 0))%DIV for s in range(SUM+1)]

    S3 = (sum(dp3[(SUM+1)//2:])*3)%DIV
    S1 = (dp1[(SUM)//2]*3)%DIV if SUM%2==0 else 0
    return (ALL - S3 + S1 + DIV) % DIV

print(main())


Measured memory_bytes: 137960
import sys
read = sys.stdin.buffer.read
input = sys.stdin.readline
input = sys.stdin.buffer.readline


#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode('utf-8')


#import numpy as np

def main():
	x,y,a,b,c=MI()
	p=LI()
	q=LI()
	r=LI()

	p.sort()
	q.sort()
	r.sort()

	p=p[a-x:]
	q=q[b-y:]

	li=p+q+r
	li.sort()
	li=li[len(li)-x-y:]
	print(sum(li))




if __name__ == "__main__":
	main()

Measured memory_bytes: 73056
#pragma comment(linker, "/STACK:512000000")
#include <bits/stdc++.h>
using namespace std;

#define all(a) a.begin(), a.end()
typedef long long li;
typedef long double ld;
void solve(__attribute__((unused)) bool);
void precalc();
clock_t start;
#define FILENAME ""

int main() {
#ifdef AIM
    string s = FILENAME;
//    assert(!s.empty());
    freopen("/home/alexandero/ClionProjects/cryptozoology/input.txt", "r", stdin);
#else
//    freopen(FILENAME ".in", "r", stdin);
//    freopen(FILENAME ".out", "w", stdout);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
#endif
    start = clock();
    int t = 1;
#ifndef AIM
    cout.sync_with_stdio(0);
    cin.tie(0);
#endif
    precalc();
    cout.precision(10);
    cout << fixed;
    //cin >> t;
    int testNum = 1;
    while (t--) {
        //cout << "Case #" << testNum++ << ": ";
        solve(true);
    }
    cout.flush();
#ifdef AIM1
    while (true) {
      solve(false);
  }
#endif

#ifdef AIM
    cout.flush();
    auto end = clock();

    usleep(10000);
    print_stats(end - start);
    usleep(10000);
#endif

    return 0;
}

template<typename T>
T binpow(T q, T w, T mod) {
    if (!w)
        return 1 % mod;
    if (w & 1)
        return q * 1LL * binpow(q, w - 1, mod) % mod;
    return binpow(q * 1LL * q % mod, w / 2, mod);
}

template<typename T>
T gcd(T q, T w) {
    while (w) {
        q %= w;
        swap(q, w);
    }
    return q;
}
template<typename T>
T lcm(T q, T w) {
    return q / gcd(q, w) * w;
}

template <typename T>
void make_unique(vector<T>& a) {
    sort(all(a));
    a.erase(unique(all(a)), a.end());
}

template<typename T>
void relax_min(T& cur, T val) {
    cur = min(cur, val);
}

template<typename T>
void relax_max(T& cur, T val) {
    cur = max(cur, val);
}

void precalc() {
}

//#define int li
//const int mod = 1000000007;

void solve(__attribute__((unused)) bool read) {
    int n;
    cin >> n;
    int res = (int)1e9;
    auto get_sum = [&] (int cur) {
        int res = 0;
        while (cur) {
            res += cur % 10;
            cur /= 10;
        }
        return res;
    };
    for (int a = 1; a < n; ++a) {
        relax_min(res, get_sum(a) + get_sum(n - a));
    }
    cout << res << "\n";
}

Measured memory_bytes: 256
while True:
  m,f,r=map(int,input().split())
  if m== -1 and f == -1 and r == -1 : break
    
  if m==-1 or f ==-1:
    print("F")

  elif m + f >=80:
    print("A")

  elif m+f <<80 and m + f >=65:
    print("B")
  
  elif (m+f <<65 and m + f >=50) or (m+f <<50 and m + f >=30 and r >=50):
    print("C")
  
  elif m+f <<50 and m + f >=30:
    print("D") 
  
  else:
    print("F") 


Measured memory_bytes: 5596
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int[][] C = new int[3][3];
		for(int i = 0;i < 3;i++) {
			for(int j = 0;j < 3;j++) {
				C[i][j] = Integer.parseInt(sc.next());
			}
		}
		sc.close();
		int[] a = new int[3];
		int[] b = new int[3];
		a[0] = 0;
		b[0] = C[0][0];
		b[1] = C[0][1];
		b[2] = C[0][2];
		a[1] = C[1][0] - b[0];
		a[2] = C[2][0] - b[0];
		String ans = "Yes";
		for(int i = 0;i < 3;i++) {
			for(int j = 0;j < 3;j++) {
				if(a[i] + b[j] != C[i][j]) {
					ans = "No";
				}
			}
		}
		System.out.println(ans);
	}
}

Measured memory_bytes: 23764
#include <bits/stdc++.h>
#define REP(i, n) for (int i=0, i##_len=(n); i<i##_len; ++i)
#define FOR(i, a, b) for (int i=(a); i<(b); ++i)
using ll = long long;
using namespace std;

int main()
{
    int N, A, B;
    cin >> N >> A >> B;

    int P[N];
    REP(i, N) cin >> P[i];

    int a = 0;
    int b = 0;
    int c = 0;
    REP(i, N)
    {
        if (P[i] <= A) ++a;
        else if (P[i] <= B) ++b;
        else ++c;
    }

    cout << min(a, min(b, c)) << endl;
    return 0;
}


Measured memory_bytes: 256
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class T>
using Table = vector<vector<T>>;
const ld eps=1e-9;

//// < "D:\D_Download\Visual Studio 2015\Projects\programing_contest_c++\Debug\a.txt"
int main() {
	int a, b, c, d; cin >> a >> b >> c >> d;
	int sum = a + b + c + d;
	cout << sum / 60 << endl << sum % 60 << endl;
	return 0;
}

Measured memory_bytes: 3088
#include<bits/stdc++.h>
#define ll long long int
#define pb push_back
#define mod 1000000007
using namespace std;

int main() {
	ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll h;
    cin >> h;
    ll ans = 1;
    while(h)
    {
    	ans *= 2;
    	h >>= 1;
	}
	ans--;
	cout << ans << "\n";
    
	return 0;
}



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

#define REP(i, n) for(int (i)=0;(i)<(n);++(i))
#define REPV(iter, v) for(auto (iter)=(v).begin(); (iter)!=(v).end();++(iter))
#define ALL(v) (v).begin(),(v).end()

#define MOD 1000000007

using namespace std;

typedef long long ll;

int main()
{
    ll N, M;
    cin >> N >> M;
    vector<ll> x(N), y(N), z(N);
    REP(i, N)
    {
        cin >> x[i] >> y[i] >> z[i];
    }

    ll ans = 0;
    for (int i = 0; i <= 7; ++i)
    {
        ll signX, signY, signZ;
        signX = (i >> 0) & 1 ? -1 : 1;
        signY = (i >> 1) & 1 ? -1 : 1;
        signZ = (i >> 2) & 1 ? -1 : 1;
        vector<ll> sumV(N);
        REP(i, N)
        {
            ll sumE = signX * x[i] + signY * y[i] + signZ * z[i];
            sumV[i] = sumE;
        }
        sort(ALL(sumV));
        reverse(ALL(sumV));
        ll sumCake = 0;
        REP(i, M)
        {
            sumCake += sumV[i];
        }
        ans = max(ans, sumCake);
    }
    

    cout << ans << endl;
}


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

using namespace std;

long long n;
long long cnt = 0, ans = 0, num = 0;
long long a[20];

void div(long long x)
{ 
	while(x) 
	{ 
		a[cnt] = x % 10; 
		if (a[cnt] == 9) num++;
		x /= 10; 
		cnt++;
	} 
	return;
}

int main()
{
	ios::sync_with_stdio(false);
	cin >> n;
	div(n);
	if (num == cnt) { cout << cnt * 9 << endl; return 0; }
	cnt--;
	for (long long i = 0; i < cnt; i++) ans += 9;
	bool vis = false;
	for (int i = 0; i < cnt; i++) 
		if (a[i] != 9) vis = true;
	if (vis == true) ans += (a[cnt] - 1);
	else ans += a[cnt];
	cout << ans << endl;
	return 0;
}

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

int main() {
  string a,b,c;
  cin >> a >> b >> c;
  a.at(0)+=(int)'A'-(int)'a';
  b.at(0)+=(int)'A'-(int)'a';
  c.at(0)+=(int)'A'-(int)'a';
  cout << a.at(0) << b.at(0) << c.at(0) << endl;
}

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

long long a, b;
long long nr = 1;

int main() {
    cin >> a >> b;
    long long n = __gcd(a, b);
    for(long long i = 2; i * i <= n; i++) {
        if(n % i == 0) {
            nr++;
            while(n % i == 0) {
                n /= i;
            }
        }
    }
    if(n > 1) {
        nr++;
    }
    cout << nr;
    return 0;
}

Measured memory_bytes: 3640
n = int(input())

a = list(map(int, input().split()))

a = sorted(a,reverse = True)

co = 2
ans = a[0]
ind = 1

while True:
    if co + 1 < n:
        ans += a[ind] * 2
        co += 2
        ind += 1
    elif co + 1 == n:
        ans += a[ind]
        break
    else:
        break

print(ans)


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

int main(){
    ll n;
    cin >> n;
    ll ans = n * (n-1)/2;
    cout << ans << endl;
}

Measured memory_bytes: 3616
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long int ll;

int N, K;
ll x[100010];

int main(){
	cin >> N >> K;
	for(int i = 0; i < N; i++) cin >> x[i];
	ll res = 1LL << 60;
	for(int i = K - 1; i < N; i++){
		ll d = min(abs(x[i]), abs(x[i - (K - 1)]));
		if(x[i] * x[i - (K - 1)] < 0) res = min(res, d + abs(x[i - (K - 1)] - x[i]));
		else res = min(res, max(abs(x[i]), abs(x[i - (K - 1)])));
	}
	cout << res << endl;
	return 0;
}


Measured memory_bytes: 1024
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <algorithm>
#include <string>
#include <math.h>
#include <limits.h>
#include <stack>
#include <complex>
#include <stdlib.h>
#include <stdio.h>
#include <functional>
#include <cfloat>
#include <math.h>
#include <numeric>
#include <string.h>
#include <sys/time.h>
#include <random>


#define fs first
#define sc second
#define endl "\n"

using namespace std;

typedef long long ll;
typedef unsigned int uint;
typedef pair<ll, ll> P;


int main(){
    ll n, m;    cin >> n >> m;
    ll su = 0;

    for(int i = 0; i < m; i++){
        int x;  cin >> x;
        su += x;
    }

    if(su > n){
        cout << -1 << endl;
    }
    else{
        cout << n - su << endl;
    }

    return 0;
}


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

int main() {
  
  //sが回分∧(n-1)/2のとこも回分∧(n+3)/2も回分
  
  string s;
  cin >> s;
  
  int size = s.size();
  int t = size - 1; 
  
  int ans = 0;
  int a = 0;
  int b = 0;
  int c = 0;
  for(int i = 0; i < size; i++){
    int k = t - i;
    if(s.at(i) == s.at(k)) a++;
  }
  if(a == size) ans++;
  
  
  for(int i = 0; i < t/2; i++){
    int k = t - i;
    if(s.at(i) == s.at(k)) b++;
  }
  if(b ==  t/2) ans++;
  
  int d = (size + 3)  / 2 - 1;
  int p = size - 1;
  for(int i = d; i < size; i++){
    if(s.at(i) == s.at(p)) c++;
    p--;
  }
  int q = size - d ;
  if(c == q) ans++;
  
  if(ans == 3){
    
    cout << "Yes" << endl;
    

  }
  else{
    cout << "No" << endl;
  }
}



Measured memory_bytes: 3624
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using vvi = vector<vi>;
using vvl = vector<vl>;
const ll INF = 1LL << 60;
const ll MOD = 1000000007;
template <class T>
bool chmax(T &a, const T &b) {
    return (a < b) ? (a = b, 1) : 0;
}
template <class T>
bool chmin(T &a, const T &b) {
    return (b < a) ? (a = b, 1) : 0;
}

int main() {
    ll k;
    cin >> k;
    int n = 50;
    vl a(n, 49 + k / 50 - k % 50);
    for (int i = 0; i < k % 50; ++i) {
        a[i] += 50;
    }
    cout << n << endl;
    for (int i = 0; i < 50; ++i) {
        cout << a[i];
        if (i != 49)
            cout << " ";
        else
            cout << endl;
    }

    return 0;
}

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

int main()
{
  int R, G, B, N;
  int res=0;
  cin >> R>>G>>B>>N;

  for(int r=0; r<=N/R; r++) {
    for(int g=0; g<=N/G; g++) {
      int n = N - R*r - G*g;
      if (n%B==0 && n >= 0) {
        //printf("%d %d %d\n", r, g, n/B);                                      
        res++;
      }
    }
  }

  cout << res << endl;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll n,k;
    string s;
    cin>>n>>k>>s;
    k--;
    s[k]=char('a'+(s[k]-'A'));
    cout<<s;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define PI acos(-1)
#define eq(x,y) (fabs((x)-(y)) < eps)
#define debug(x) cout<<x<<endl;
#define pb push_back
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
using namespace std;
typedef long long ll;
typedef unsigned long long llu;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const int inf=1e9+7;
const int nmax=1e5+10;
const int eps=1e-8;
const ll infll=1e15;


int main()
{
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    string ara[]={"lol","MON","TUE","WED","THU","FRI","SAT","SUN"};
    string s;
    cin>>s;

    if(s=="SUN")
        cout<<"7\n";
    else
    {
        int pos;
        for(int i=0;i<8;i++)
        {
            if(ara[i]==s)
            {
                pos=i;
                break;
            }
        }

        int ans=7-pos;
        cout<<ans<<"\n";
    }



    return 0;
}


Measured memory_bytes: 256
l,r = gets.split(" ").map{|e| e.to_i}
min = 2019
l.upto(r-1) do|i|
  (i+1).upto(r) do |j|
    min = (i*j)%2019 if min >= (i*j)%2019
    break if min == 0
  end
  break if min == 0
end

puts min


Measured memory_bytes: 1788
import collections

h, w = map(int, input().split())
s = [[""]*(w+2)]
for _ in range(h):
    _s = list(input())
    _s.insert(0, "")
    _s.append("")
    s.append(_s)
s.append([""]*(w+2))

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]

ans = 0

for _h in range(1, h+1):
    for _w in range(1, w+1):
        if s[_h][_w] == "#":
            continue

        q = collections.deque([[_h, _w]])

        a = [[-1]*(w+2) for _ in range(h+2)]
        a[_h][_w] = 0

        while 0 < len(q):
            cx, cy = q.pop()
            for _dx, _dy in zip(dx, dy):
                x = cx + _dx
                y = cy + _dy

                if s[x][y] == "." and a[x][y] == -1:
                    a[x][y] = a[cx][cy] + 1
                    q.appendleft([x, y])

        for _a in a:
            ans = max(ans, max(_a))

print(ans)


Measured memory_bytes: 3316
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int N;
string s;

bool f(vector<int> &t) {
    for(int i=1; i<=N; i++) {
        if(s[i] == 'o' && t[i]) {
            t[i+1] = 1 - t[i-1];
        } else if(s[i] == 'o') {
            t[i+1] = t[i-1];
        } else if(t[i]) {
            t[i+1] = t[i-1];
        } else {
            t[i+1] = 1 - t[i-1];
        }
    }
    if(t[0] == t[N] && t[1] == t[N+1]) {
        for(int i=0; i<N; i++) {
            if(t[i]) {
                cout << 'W';
            } else {
                cout << 'S';
            }
        }
        cout << endl;
        return true;
    } else {
        return false;
    }
}

int main(void) {
    cin >> N >> s;
    s.push_back(s[0]);
    s.push_back(s[1]);
    vector<int> t(N+2);

    t[0] = 0;
    t[1] = 0;
    if(f(t)) return 0;
    t[0] = 0;
    t[1] = 1;
    if(f(t)) return 0;
    t[0] = 1;
    t[1] = 0;
    if(f(t)) return 0;
    t[0] = 1;
    t[1] = 1;
    if(f(t)) return 0;
    cout << -1 << endl;
    return 0;
}


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

int H,W;
int cnt[50];
int fie[111][111];
int mst[5];

int ume(){
  int k = 0;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++){
      if( fie[i][j] == 0 ) {
        int rj = W-j-1, ri = H-i-1;
        fie[i][j] = k;
        fie[ri][j] = k;
        fie[ri][rj] = k;
        fie[i][rj] = k;
        k++;
      }
    }
  }
  unordered_map<int,int> mp;
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++) {
      mp[fie[i][j]]++;
    }
  }
  for( auto x : mp ){
    mst[x.second]++;
  }
}

bool check(){
  for(int i=4;i>0;i--){
    while(mst[i]>0){
      bool ch = false;
      for(int j=0;j<30;j++){
        while(cnt[j]>=i){
          cnt[j] -= i;
          mst[i]--;
          ch = true;
          if(mst[i]==0)break;
        }
        if(mst[i]==0)break;
      }
      if(!ch) return false;
    }
  }
  return true;
}

int main(){
  cin >> H >> W;
  for(int i=0;i<H;i++)
    for(int j=0;j<W;j++){
      char c; cin >> c;
      cnt[c-'a']++;
    }

  ume();
  if( check() )
    cout << "Yes" << endl;
  else
    cout << "No" << endl;

}

Measured memory_bytes: 384