akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    int H, W;
    cin >> H >> W;

    vector<vector<char>> map;
    for(int i = 0 ; i < H; i++){
        vector<char> tmp(W);
        for(int j = 0; j < W; j++){
            cin >> tmp[j];
        }

        if(count(tmp.begin(), tmp.end(), '.') != W){
            vector<char> pushVector;
            for(int j = 0; j < W; j++){
                pushVector.push_back(tmp[j]);
            }

            map.push_back(pushVector);
        }
    }

    for(int j = 0; j < map[0].size(); j++){
        int count = 0;
        for(int i = 0; i < map.size(); i++){
            if(map[i][j] == '.') count++;
        }

        if(count == map.size()){
            for(int i = 0; i < map.size(); i++){
                map[i][j] = '*';
            }
        }
    }


    for(int i = 0; i < map.size(); i++){
        for(int j = 0; j < map[i].size(); j++){
            if(map[i][j] != '*') cout << map[i][j];
        }
        cout << endl;
    }
}

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

int main() {
    int N, K; cin >> N >> K;
    string s;
    while (N > 0) {
        s.push_back('0' + N % K);
        N /= K;
    }
    cout << s.size() << endl;
}


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

void removeDuplicates(string &S) {
	char prev = '\0';
	for (auto it = S.begin(); it != S.end(); it++)
	{
		if (prev == *it) {
			S.erase(it);
			it--;
		}
		else {
			prev = *it;
		}
	}
}

int main()
{
    long n;
    string S;
	cin>>n;
	cin>>S;
	removeDuplicates(S);
	cout << S.length() << endl;
	return 0;
}

Measured memory_bytes: 512
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
typedef pair<int, int> pii;
int main() {
  int N, M;
  string S;
  cin >> N >> M >> S;
  if (S.back() == '1') {
    cout << -1 << endl;
    return 0;
  }
  int i = N;
  vector<int> path;
  while (i > 0) {
    for (int j = min(M, i); j >= 0; j--) {
      if (j == 0) {
        cout << -1 << endl;
        return 0;
      }
      if (S[i - j] == '0') {
        i -= j;
        path.push_back(j);
        break;
      }
    }
  }
  reverse(path.begin(), path.end());
  for (int p : path) {
    cout << p << " ";
  }
  cout << endl;
  return 0;
}


Measured memory_bytes: 1144
#include<bits/stdc++.h>
#define rep(i,n) for(long long i=0;i<(n);i++)
#define ll long long
using namespace std;
int main(){
    int s,w;
    cin >> s >> w;
    if(s <= w) cout << "unsafe" << endl;
    else cout << "safe" << endl;
    return 0;
}

Measured memory_bytes: 3596
fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val aList = readLine()!!.split(' ').map(String::toInt).sorted()
    val mod = n % 2
    for ((i, a) in aList.withIndex()) {
        if ((a != i && (a - 1) != i) || a % 2 == mod) {
            println(0)
            return
        }
    }

    val num = n / 2

    var answer = 1L
    for (i in 1..num) {
        answer = (answer * 2L) % 1000000007
    }
    println(answer)
}

Measured memory_bytes: 53940
//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){  
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var alist = nextIntArray();
  var blist = nextIntArray();
  var clist = nextIntArray();
  alist.sort(s);
  blist.sort(s);
  clist.sort(s);
  var output = 0;
  for(var i = 0; i < N; i++){
    var mae = binarySearch(alist, blist[i], true);
    var ato = binarySearch(clist, blist[i], false);
    output += mae * ato;
  }
  myout(output);
}
function s(a,b){
  return a - b;
}
function binarySearch(list, search, isA){
  var ng = -1;
  var ok = list.length;
  while(Math.abs(ok - ng) > 1){
    var center = Math.floor((ok + ng) / 2);
    if(isA){
      if(list[center] >= search){
        ok = center;
      }else{
        ng = center;
      }
    }else{
      if(list[center] > search){
        ok = center;
      }else{
        ng = center;
      }
    }
  }
  if(isA){
    return ng + 1;
  }else{
    if(ok != list.length && list[ok] == search){
      ng++;
    }
    return list.length - (ng + 1);
  }
}

Measured memory_bytes: 59500
s = input().split()[0]
word_list = ['dream', 'dreamer', 'erase', 'eraser']

# erasedream
work_s = s
kumiawase = []

def check_end(text: str, k_word_list):
    ok_word = []
    for word in k_word_list:
        if text.endswith(word):
            ok_word.append(word)
    return ok_word

answer = 'NO'

while work_s:
    ok_word = check_end(work_s, word_list)
    if not ok_word:
        break

    # 後ろから見た場合かぶらないので、これは1回しか動かないはず
    for next_word in ok_word:
        work_s = work_s[:-len(next_word)]
else:
    answer = 'YES'

print(answer)

Measured memory_bytes: 3316
#include <stdio.h>
#include <string.h>

int main(void)
{
	char joi[1000001];
	char *p;
	int i, len;
	int rj, ro, ri;
	int level;

	scanf("%s", joi);
	len = strlen(joi);

	level = 0;
	for (i = 0; i < len; ){
		if (joi[i] == 'J'){
			for (rj = 0; joi[i + rj] == 'J'; rj++);
			for (ro = 0; joi[i + rj + ro] == 'O'; ro++);
			for (ri = 0; joi[i + rj + ro + ri] == 'I'; ri++);

			if (!(ri < ro || rj < ro)){
				level = fmax(level, ro);
			}
			i = i + rj + ro + ri;
		}
		else {
			i++;
		}
	}

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

	return (0);
}

Measured memory_bytes: 1520
/*
author:Rahul Chocha
school of eng. and applied science
*/

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define MAXI INT_MAX
#define MINI INT_MIN
#define din(t) long long t; cin >> t;
#define fi(i, l, r, d) for (i = l; i < r; i += d)
#define fd(i, l, r, d) for (i = l - 1; i >= r; i -= d)
#define pb push_back
#define mp make_pair


void speed_up()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
}

ll int findMinDiff(ll int arr[], ll int n) 
{ 
   // Sort array in non-decreasing order 
   sort(arr, arr+n); 
  
   // Initialize difference as infinite 
   ll int diff = INT_MAX; 
  
   // Find the min diff by comparing adjacent 
   // pairs in sorted array 
   for (ll int i=0; i<n-1; i++) 
      if (arr[i+1] - arr[i] > diff) 
          diff = arr[i+1] - arr[i]; 
  
   // Return min diff 
   return diff; 
}
int main()
{   
	speed_up();
	//din(t)
	ll t=1;
	while(t--){
      din(a) din(b) din(c) din(d)
      cout<<max(max(max(a,b)*c,max(a,b)*d),max(min(a,b)*c,min(a,b)*d));  
	}

	
}


Measured memory_bytes: 3640
/*
* @Author Silviase(@silviasetitech)
* For ProCon
*/

import java.util.*;
import java.lang.*;
import java.math.*;

class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        if (n % 11  <= 6) {
            System.out.println( (n / 11) * 2 + (n % 11 + 10)/11 );
        } else {
            System.out.println( (n / 11) * 2 + 2 );
        }
        sc.close();
    }
}





Measured memory_bytes: 21716
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<array>
#include<bitset>
#include<cassert>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<functional>
#include<limits>
#include<list>
#include<map>
#include<numeric>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<queue>
#include<vector>
using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define RFOR(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define REP(i,n) for(int i=0;i<(n);i++)
#define RREP(i,n) for(int i=(n)-1;i>=0;i--)
#define ALL(a) (a).begin(),(a).end()
#define DUMP(o) {cerr<<#o<<" "<<o<<endl;}
#define DUMPC(o) {cerr<<#o; for(auto &e:(o))cerr<<" "<<e;cerr<<endl;}
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
const int MOD = 1e9 + 7;

//??¨????????????????????????
//n??\????????£??´??°????´???°???????????°???????????????is_prime[]???????´?
void eratos(int n, bool is_prime[]) {
	fill(is_prime, is_prime + n + 1, true);
	is_prime[0] = is_prime[1] = false;
	for (int i = 2; i*i <= n; i++)
		if (is_prime[i]) {
			int j = i + i;
			while (j <= n) {
				is_prime[j] = false;
				j = j + i;
			}
		}
}

signed main() {
	bool is_prime[200000];
	eratos(200000, is_prime);
	int prime[10001] = {};
	int cnt = 1;
	FOR(i, 2, 200000) {
		if (is_prime[i]) {
			prime[cnt] = i;
			cnt++;
		}
	}
	for (int n; cin >> n&&n;) {
		ll ans = 0;
		FOR(i, 1, n + 1)ans += prime[i];
		cout << ans << endl;
	}
	return 0;
}

Measured memory_bytes: 3336
#include <stdio.h>
#include <string.h>

void swap(int *a, int *b)
{
	*a += *b;
	*b = *a - *b;
	*a -= *b;
}

int main(void)
{
	int n, m;
	int i, j;
	int q;
	int data[1024];
	int idx[1024];
	
	while (1){
		scanf("%d %d", &n, &m);
		
		if (n == 0 && m == 0){
			break;
		}
		
		memset(data, 0, sizeof(data));
		for (i = 0; i < n; i++){
			for (j = 0; j < m; j++){
				scanf("%d", &q);
				data[j] += q;
				idx[j] = j + 1;
			}
		}
		
		for (i = 0; i < m - 1; i++){
			for (j = 0; j < m - i - 1; j++){
				if (data[j] < data[j + 1]){
					swap(&data[j], &data[j + 1]);
					swap(&idx[j], &idx[j + 1]);
				}
			}
		}
		
		for (i = 0; i < m; i++){
			printf("%d%c", idx[i], i == m - 1 ? '\n' : ' ');
		}
	}
	
	return (0);
}

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

int main(void) {
  char str1[4], str2[4];
  int a, b;
  int i;
  double sq;

  scanf("%s%s", str1, str2);
  a = atoi(str1);

  for (i = 0; i < strlen(str2); i++) {
    a *= 10;
  }
  a += atoi(str2);
  //printf("a = %d\n", a);                                                                                                                                                                                         
  sq = sqrt(a);
  printf("%s\n", ((double)((int)sq)) == sq ? "Yes" : "No" );

  return 0;
}

Measured memory_bytes: 128
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.readline

n,q=map(int,input().split())
g=[[]for _ in range(n)]
res=[0 for _ in range(n)]
for _ in range(n-1):
    a,b=map(int,input().split())
    a-=1
    b-=1
    g[a].append(b)
    g[b].append(a)

for _ in range(q):
    p,x=map(int,input().split())
    res[p-1]+=x
    


def my_add(v,par):
    for vn in g[v]:
        if vn==par:
            continue
        res[vn]+=res[v]
        my_add(vn,v)

my_add(0,-1)
print(*res)

Measured memory_bytes: 230960
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;


public class Test
{	
    public static void Main()
	{
	    int[] nums = Console.ReadLine().Split(' ').Select(s => int.Parse(s)).ToArray();

        int[] ans = new int[3];
        ans[0] = nums[0] + nums[1];
        ans[1] = nums[0] + nums[2];
        ans[2] = nums[1] + nums[2];
        Array.Sort(ans);
        
        Console.WriteLine(ans[0]);
        
	}
}

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

using namespace std;

int main() {
    long long k;
    cin >> k;

    vector<bool> m(k, false);
    long long res = 1;
    for (long long i = 1, j = 7 % k; !m[j]; i *= 10, i %= k, j += 7 * i, j %= k) {
        m[j] = true;
        if (j == 0) {
            break;
        }

        res++;
    }

    cout << (m[0] ? res : -1) << endl;
}


Measured memory_bytes: 3728
import bisect, collections, copy, heapq, itertools, math, string
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int, sys.stdin.readline().rstrip().split())
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split())

mod = 10 ** 9 + 7
N, K = MI()
def num(self):
    return (-2 * pow(self, 3) + 3 * N * pow(self, 2) + (3 * N + 8) * self) // 6
ans = num(N + 1) - num(K - 1)
print(ans % mod)

Measured memory_bytes: 74664
#include <cstdio>

int main() {
  int n;
  scanf("%d", &n);
  int last = 0;
  long long ans = 0;
  for (int i = 0; i < n; i++) {
    int x;
    scanf("%d", &x);
    int can = (x - 1) / (last + 1);
    if (can >= 1) {
      ans += can;
    } else {
      if (last < x) {
        last = x;
      }
    }
    if (i == 0) last = 1;
  }
  printf("%lld\n", ans);
}

Measured memory_bytes: 256
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;

const int MaxN = 1e6;
int n;
long long l[MaxN + 5];

int main()
{
	scanf("%d", &n);
	l[0] = 2, l[1] = 1; 
	for(int i = 2; i <= n; i++)
		l[i] = l[i - 2] + l[i - 1];
		printf("%lld\n", l[n]);
		return 0;
}


Measured memory_bytes: 384
#include <iostream>
#include <utility>
#include <map>
#include <vector>
#include <algorithm>
#include <queue>
#include <math.h>
#include <stack>
#include <set>
#include <deque>
#include <cmath>
#include <cassert>

using namespace std;
typedef long long ll;
ll mod = 1e9+7;
#define rep(i,n) for(int i = 0; i < (n); ++i)

vector<int> dfs(int n, int s, vector<vector<int>> &g) {
    vector<int> color(n, 0);
    vector<int> ret;
    queue<pair<int, int>> que;
    que.push(make_pair(s, 1));
    ret.push_back(1);
    color[s] = 1;
    while(!que.empty()) {
        pair<int, int> now = que.front();
        que.pop();
        for (auto v: g[now.first]) {
            if (color[v] == 0) {
                color[v] = -color[now.first];
                que.push(make_pair(v, now.second+1));
                ret.push_back(now.second+1);
            }
            if (color[v] != -color[now.first]) {
                ret.clear();
                return ret;
            }
        }
    }
    return ret;
}

int main() {
    int n;
    cin >> n;
    vector<vector<int>> g(n);
    rep(i, n) rep(j, n) {
        char s;
        cin >> s;
        if (s == '1') {
            g[i].push_back(j);
        }
    }
    int ans = -1;
    rep(i, n) {
        auto v = dfs(n, i, g);
        if (!v.empty()) {
            ans = max(ans, *max_element(v.begin(), v.end()));
        }
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 3772
#include"bits/stdc++.h"
using namespace std;
using ll = int64_t;

int main() {
    string S;
    cin >> S;
    ll ans = 0;
    ll b = 0;
    for (ll i = 0; i < S.size(); i++) {
        if (S[i] == 'B') {
            b++;
        } else {
            ans += b;
        }
    }

    cout << ans << endl;
}

Measured memory_bytes: 640
import java.util.Scanner;

public class Main {
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Cij = (k=1...m) AikBkj
        // Cnl = Anm x Bml
        
        // input n,m,l
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int l = scanner.nextInt();
        
        // create Anm
        int[][] Anm = new int[n][m];
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                Anm[i][j] = scanner.nextInt();
            }
        }
        
        // create Bml
        int[][] Bml = new int[m][l];
        for(int i=0; i<m; i++){
            for(int j=0; j<l; j++){
                Bml[i][j] = scanner.nextInt();
            }
        }
        
        // create Cnl
        long[][] Cnl = new long[n][l];
        for(int iN=0; iN<n; iN++){
            for(int kM=0; kM<m; kM++){            
                for(int jL=0; jL<l; jL++){
                    Cnl[iN][jL] += Anm[iN][kM] * Bml[kM][jL];
                }
            }
        }
        
        // display
        printArray(Cnl);

    }
    
    public static void printArray(long[][] array) {
        int row = array.length;
        int width = array[0].length;
        for(int i=0; i<row; i++){
            for(int j=0; j<width; j++){
                System.out.print(array[i][j]);
                if (j != width-1) { System.out.print(" "); }
            }
            System.out.println();
        }
    }
    
}


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

int main(){
  string s,t;cin>>s>>t;
  int cnt=0;
  for(int i=0;i<3;i++){
    if(s[i]==t[i]){
      cnt++;
    }
  }
  cout<<cnt<<endl;
}

Measured memory_bytes: 256
#include <iostream>
using namespace std; 
int main(void){

  int n;
  string s;
  cin >> n >> s;

  if (n % 2 != 0){
    cout << "No"<< endl;
    return 0;
  }
    
  for(int i; i * 2 < n; i++){
    if (s[i] != s[i + n / 2]){
      cout << "No"<< endl;
      return 0;
    }
  }
   
  cout << "Yes" << endl;
  return 0;
}


Measured memory_bytes: 256
// 見せてやるぜ、奇跡ってやつをよぉ……
#include <iostream>
#include <array>
#include <algorithm>
#include <vector>
#include <bitset>
#include <set>
#include <unordered_set>
#include <cmath>
#include <complex>
#include <deque>
#include <iterator>
#include <numeric>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <limits>
#include <iomanip>
#include <functional>
#include <cassert>
using namespace std;

using ll=long long;
template<class T> using V = vector<T>;
template<class T, class U> using P = pair<T, U>;
using vll = V<ll>;
using vvll = V<vll>;
#define rep(i, k, n) for (ll i=k; i<(ll)n; ++i)
#define REP(i, n) rep(i, 0, n)
#define ALL(v) v.begin(),v.end()
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; }
#define DEBUG_VLL(vec) REP(sz, vec.size()) std::cerr<<vec[sz]<<(sz==vec.size()-1?'\n':' ');

const ll MOD = 1000000007;
const ll HIGHINF = (ll)1e18;
const int INF = 1e9;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    V<int> p(n);
    for (int i = 0; i < n; i++) cin >> p[i];
    
    int minp = n + 1;
    int ans = 0;
    for (int i = 0; i < n; i++) {
        if (p[i] < minp) ans++;
        chmin(minp, p[i]);
    }
    cout << ans << '\n';
    return 0;
}


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

using namespace std;

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

#define SZ(x) ((int)(x).size())
#define ALL(x) (x).begin(),(x).end()

#define DUMP(x) cerr<<#x<<" = "<<(x)<<endl
#define DEBUG(x) cerr<<#x<<" = "<<(x)<<" (L"<<__LINE__<<")"<<endl;

template<class T>
ostream &operator<<(ostream &os, const vector <T> &v) {
    os << "[";
    REP(i, SZ(v)) {
        if (i) os << ", ";
        os << v[i];
    }
    return os << "]";
}

template<class T, class U>
ostream &operator<<(ostream &os, const pair <T, U> &p) {
    return os << "(" << p.first << " " << p.second << ")";
}

template<class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using P = pair<int, int>;
using vi = vector<int>;
using vll = vector<ll>;
using vvi = vector<vi>;
using vvll = vector<vll>;

const ll MOD = 1e9 + 7;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;
const ld eps = 1e-9;

template<typename T>
struct edge {
    int src, to;
    T cost;
};

template<typename T>
using Graph = vector<vector<edge<T>>>;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);

    // ifstream in("in.txt");
    // cin.rdbuf(in.rdbuf());

    int n, m; cin >> n >> m;
    string s; cin >> s;
    vvi g(n);
    vi dega(n),degb(n);
    REP(i, m) {
        int u, v; cin >> u >> v; --u, --v;
        g[u].push_back(v);
        g[v].push_back(u);
        if (s[u] == 'A') ++dega[v];
        else ++degb[v];
        if (s[v] == 'A') ++dega[u];
        else ++degb[u];
    }

    queue<int> que;
    REP(v, n) {
        if (dega[v] == 0 or degb[v] == 0) {
            que.push(v);
        }
    }

    vi valid(n, 1);

    while (!que.empty()) {
        int v = que.front(); que.pop();
        if (!valid[v]) continue;
        valid[v] = 0;
        dega[v] = degb[v] = 0;

        for (int u : g[v]) {
            if (!valid[u]) continue;

            if (s[v] == 'A') --dega[u];
            else --degb[u];
            if (dega[u] == 0 or degb[u] == 0) {
                que.push(u);
            }
        }
    }

    int ans = 0;
    REP(v, n) {
        if (valid[v]) ans = 1;
    }


    cout << (ans ? "Yes" : "No") << endl;

    return 0;
}


Measured memory_bytes: 12880
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

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

#処理内容
def main():
	T = list(input())
	N = len(T)
	for i in range(N):
		if T[i] == "?":
			T[i] = "D"

	print("".join(T))

if __name__ == '__main__':
	main()

Measured memory_bytes: 10936
const val mod = 1000000007L

fun modpow(n:Int,p:Long = mod-2L):Long = when {
	p==0L->1L
	p%2==1L->n*modpow(n,p-1)%mod
	else-> {
		val d = modpow(n,p/2)
		d*d%mod
	}
}

fun nCr(n:Int,r:Int,modpowCache:Long):Long = (n-r+1L..n).asSequence().fold(modpowCache) {a,b-> a*b%mod}
fun modpowCache(r:Int) = (2..r).asSequence().map {modpow(it)}.fold(1L) {a,b-> a*b%mod}

fun main(args:Array<String>) {
	val s = java.util.Scanner(System.`in`)
	val n = s.nextInt()
	val k = s.nextInt()-2
	if(k==-1) {
		println(0)
		return
	}
	val a = LongArray(n) {s.nextLong()}.sorted()

	val modpowCache = modpowCache(k)
	val cache:LongArray = if(k==0) LongArray(n-1) {modpowCache}
	else {
		val t = LongArray(n-1) {0L}
		t[k] = nCr(k,k,modpowCache)
		for(i in k+1..n-2) {
			t[i] = t[i-1]*i%mod*modpow(i-k)%mod
		}
		t
	}
	for(i in 1..n-2)
		cache[i] = (cache[i]+cache[i-1])%mod

	val r = a.indices.map {i->
		val l = if(i<1) 0 else cache[i-1]
		val m = if(i>n-2) 0 else cache[n-2-i]
		((l-m+mod*2)%mod*a[i]%mod+mod)%mod
	}.fold(0L) {a,b-> (a+b)%mod}
	println(r)
}


Measured memory_bytes: 56800
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author palayutm
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            String target = "MARCH";
            long[] a = new long[5];
            int n = in.nextInt();
            for (int i = 0; i < n; i++) {
                String s = in.next();
                char c = s.charAt(0);
                if (target.indexOf(c) >= 0) {
                    a[target.indexOf(c)]++;
                }
            }
            long ans = 0;
            for (int i = 0; i < 5; i++) {
                for (int j = i + 1; j < 5; j++) {
                    for (int k = j + 1; k < 5; k++) {
                        ans += a[i] * a[j] * a[k];
                    }
                }
            }
            out.println(ans);
        }

    }

    static class OutputWriter extends PrintWriter {
        public OutputWriter(OutputStream out) {
            super(out);
        }

        public OutputWriter(Writer out) {
            super(out);
        }

        public void close() {
            super.close();
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}



Measured memory_bytes: 34468
#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fst first
#define snd second
using namespace std;

typedef long long ll;
typedef double db;
typedef long double ldb;

template<class T> inline void checkmin(T &a,const T &b){if(b<a) a=b;}
template<class T> inline void checkmax(T &a,const T &b){if(b>a) a=b;}

const int inf=1e9+10;

int n; 

int main(){
	scanf("%d",&n);
	for(int i=1;i<=360;i++){
		if(n*i%360==0){
			printf("%d\n",i);
			return 0;
		}
	} 
	return 0;
}


Measured memory_bytes: 3812
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

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

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

fn run() {
    input! {
        n: usize,
        m: usize,
    }
    let ans = n * m;
    println!("{}", ans);
}

fn main() {
    run();
}



Measured memory_bytes: 5032
#include <iostream>
#include <array>
#define repeat(i,n) for (int i = 0; (i) < int(n); ++(i))
typedef long long ll;
using namespace std;
template <class T> void setmax(T & a, T const & b) { if (a < b) a = b; }
/*
 *  OO  IIII  Jjjj  lllL
 *  OO  iiii  JJJj  lLLL
 *
 *  L IIII LLL
 *  LLL iiii L
 *
 *  L IIII J
 *  LLL  JJJ
 */
enum tile_t { I, O, T, J, L, S, Z };
ll f(array<ll, 7> a, int jil) {
    a[I] -= jil;
    a[J] -= jil;
    a[L] -= jil;
    if (a[I] < 0 or a[J] < 0 or a[L] < 0) return -1;
    ll k = 0;
    k += jil * 3;
    k += a[I] / 2 * 2; a[I] %= 2;
    k += a[J] / 2 * 2; a[J] %= 2;
    k += a[L] / 2 * 2; a[L] %= 2;
    k += a[O]; a[O] = 0;
    return k;
}
int main() {
    array<ll, 7> a; repeat (i,7) cin >> a[i];
    ll k = 0;
    repeat (jil,3) setmax(k, f(a, jil));
    cout << k << endl;
    return 0;
}


Measured memory_bytes: 256
n = int(input())
#a,b = (int(i) for i in input().split())
a = list(int(i) for i in input().split())
ans = a[0]
for i in range(1,n):
	ans*= a[i]
	if ans > 10 ** 18:
		ans = -1
		break
if ans == -1:
	for i in range(n):
		if a[i] ==0:
			ans = 0
			break
print(ans)

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

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

        int[] a = new int[N];
        for(int i = 0; i < N; i++) {
            a[i] = sc.nextInt();
        }
        int count = 0;
        for(int i = 0; i < N; i++) {
            if(i != N-1) {
                if(a[i+1] == a[i] && a[i+1] != -1 && a[i] != -1) {
                    a[i+1] = -1;
                    count++;
                    continue;
                }
            } 
            if(i != 0) {
                if(a[i-1] == a[i] && a[i-1] != -1 && a[i] != -1) {
                    a[i] = -1;
                    count++;
                    continue;
                }
            }
        }
        System.out.println(count);
    }
}

Measured memory_bytes: 22100
#include <bits/stdc++.h>
using namespace std;
#define fastIO                        \
	ios_base::sync_with_stdio(false); \
	cin.tie(NULL);                    \
	cout.tie(NULL)
// g++ -std=c++11 -O2 -Wall *.cpp -o *
#define eps 1e-9
#define MAX 10000010
#define MOD 1000000007
#define PI 3.14159265358979323846
#define Fi first
#define Se second
#define PB push_back
#define MP make_pair
#define all(a) a.begin(), a.end()
#define allr(a) a.rbegin(), a.rend()
#define maxof(a) *max_element(all(a))
typedef long long ll;


int main()
{
	fastIO;
	// freopen("input.txt", "r", stdin);
	// freopen("output.out", "w", stdout);

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

	vector<ll> A, Apos, Aneg;
	for (int i = 0; i < N; i++)
	{
		ll a;
		cin >> a;
		A.PB(abs(a));
		if (a > 0) Apos.PB(a);
		if (a < 0) Aneg.PB(-a);
	}
	int szp = Apos.size(), szn = Aneg.size();

	ll ans = 1;

	if (szp + szn / 2 * 2 >= K && (K % 2 == 0 || szp > 0))
	{
		sort(Apos.rbegin(), Apos.rend());
		sort(Aneg.rbegin(), Aneg.rend());
		if (K % 2)
			ans = Apos[0];
		vector<ll> V;
		for (int i = K % 2; i + 1 < szp; i += 2)
			V.PB(Apos[i] * Apos[i + 1]);
		for (int i = 0; i + 1 < szn; i += 2)
			V.PB(Aneg[i] * Aneg[i + 1]);
		sort(allr(V));
		for (int i = 0; i < K / 2; i++)
			ans = ans * (V[i] % MOD) % MOD;
	}
	else
	{
		sort(all(A));
		for (int i = 0; i < K; i++)
			ans = ans * A[i] % MOD;
		ans = (MOD - ans) % MOD;
	}
	cout << ans << endl;

	cout << "\n";
	return 0;
}


Measured memory_bytes: 8392
if __name__=="__main__":
  N=int(input())
  x=[int(i) for i in input().split()]
  ans=0
  for i in range(1,len(x)):
    if x[i]<x[i-1]:
      #print(x[i-1]-x[i])
      ans+=(x[i-1]-x[i])
      x[i]+=(x[i-1]-x[i])
  print(ans)

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

int N;
void input() { cin >> N; }
void solve() { cout << ((N % 1000 != 0) ? (1000 - N % 1000) : 0) << endl; }

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

Measured memory_bytes: 3640
R, G, B, N = map(int, input().split())

ans = 0
rsum = 0
for r in range(0, N+1):
    if N < rsum:
        break
    rgsum = rsum
    for g in range(0, N+1):
        if N < rgsum:
            break
        left = N - rgsum
        if left % B == 0:
            ans += 1
        rgsum += G
    rsum += R

print(ans)


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


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

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


int main()
{
	cin.tie(0); ios_base::sync_with_stdio(false);
	int h, w;;
	cin >> h >>w;
	vector<string> ba(h);
	rep(i, h) cin >>ba[i];
	vector<VI> dp(h+2, VI(w+2, MD));
	dp[0][0] = (ba[0][0]=='#');
	rep(i, h) rep(j, w){
		if(i) amin(dp[i][j], dp[i-1][j] +(ba[i][j] != ba[i-1][j]));
		if(j) amin(dp[i][j], dp[i][j-1] +(ba[i][j] != ba[i][j-1]));
	}
	//for(auto xl: dp){for(auto x :xl) cerr<<x<<" ";dbg();}
	int ans = (dp[h-1][w-1] + 1) /2;
	cout << ans <<"\n";
	return 0;


}


Measured memory_bytes: 384
#include <stdio.h>
int main(void)
{
    int a, b;
    int d, r;
    double f;

    scanf("%d", &a);
    scanf("%d", &b);

    d = a / b;
    r = a % b;
    f = (double)a / b;

    printf("%d %d %.5f\n", d, r, f);

    return 0;
}


Measured memory_bytes: 2148
#define _USE_MATH_DEFINES

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>

using namespace std;

int main(){
	
	long long int a, b, c;
	cin >> a >> b >> c;
	
	int ans = -1;
	
	for(int i = 0; i < 1000000; i++){
		if(a % 2 || b % 2 || c % 2){
			ans = i;
			break;
		}
		if(a == b && b == c){
			break;
		}
		long long int x, y, z;
		x = (a + b) / 2;
		y = (c + b) / 2;
		z = (a + c) / 2;
		a = x;
		b = y;
		c = z;
	}
	
	cout << ans << endl;
	
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
using namespace std;
typedef long long unsigned int ll;
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
#define REP(i, n) for (ll i = 0; i < n; i++)
int main()
{
	ll H;
	cin >> H;
	deque<ll> deq;
	ll cnt = 0;
	while (H != 1)
	{
		cnt++;
		H = H / 2;
	}
	ll r = 0;
	// cout << "cnt" << cnt << endl;
	REP(i, cnt + 1)
	{
		r += pow(2, i);
		// cout << "pow" << pow(2, i) << endl;
	}
	cout << r << endl;
	return 0;
}

Measured memory_bytes: 256
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

typedef long long LL;

const int M = 1000000007;

int N;
int a[131072];
int ans;
int count;

int main() {
    scanf("%d", &N);
    ans = 1;
    count = 0;
    for (int i = 1; i <= N; ++i) {
        scanf("%d", a + i);
        if (count * 2 + 1 > a[i]) {
            ans = (LL)ans * (count + 1) % M;
        } else {
            count ++;
        }
    }
    for (int i = 1; i <= count; ++i)
        ans = (LL)ans * i % M;
    printf("%d\n", ans);
    return 0;
}

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

using namespace std;

const bool debug = true;
#define dbg(...) if(debug) printf(__VA_ARGS__)
#define print(var) if (debug) cout << #var << " = " << var << endl

namespace {
    int N, K;
    vector<int> X, Y, C;
    void input() {
        cin >> N >> K;
        X.resize(N);
        Y.resize(N);
        C.resize(N); // 0 for W, 1 for B
        for (int i = 0; i < N; i++) {
            char c;
            cin >> X[i] >> Y[i] >> c;
            C[i] = c == 'W' ? 0 : 1;
        }
    }

    const int MAX_W = 2001;
    void solve() {
        static int F[2][MAX_W][MAX_W]; memset(F, 0, sizeof(F));

        int W = 2 * K;
        for (int i = 0; i < N; i++) {
            int x = X[i], y = Y[i], c = C[i];
            F[c][y % W][x % W]++;
        }

        int sum[2][MAX_W + 1][MAX_W + 1]; {
            for (int p = 0; p < 2; p++) {
                for (int i = 0; i <= W; i++) sum[p][i][0] = 0;
                for (int j = 0; j <= W; j++) sum[p][0][j] = 0;
                for (int i = 0; i < W; i++)
                    for (int j = 0; j < W; j++)
                        sum[p][i + 1][j + 1] = sum[p][i][j + 1] + sum[p][i + 1][j] - sum[p][i][j] + F[p][i][j];
            }
        }
        auto getSum = [&](int c, int sy, int sx, int gy, int gx) {
            return sum[c][gy][gx] - sum[c][gy][sx] - sum[c][sy][gx] + sum[c][sy][sx];
        };

        int ans = 0;
        for (int sx = 0; sx < K; sx++) {
            for (int sy = 0; sy < K; sy++) {
                for (int c = 0; c < 2; c++) {
                    int count = 
                        getSum(c, 0, 0, sy, sx) +
                        getSum(c, 0, sx + K, sy, W) +
                        getSum(c, sy + K, 0, W, sx) + 
                        getSum(c, sy + K, sx +K, W, W) +
                        getSum(c, sy, sx, sy + K, sx + K) +
                        getSum(!c, sy, 0, sy + K, sx) +
                        getSum(!c, 0, sx, sy, sx + K) + 
                        getSum(!c, sy + K, sx, W, sx + K) +
                        getSum(!c, sy, sx + K, sy + K, W);
                    ans = max(ans, count);
                }
            }
        }
        cout << ans << endl;

    }
}

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



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

int d,ans[365],c[26],s[365][26],last[26],tlast[26],S[365][26];
const int INF=1e9;

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

void FIN(int a){
  if(a){
    ofstream fout("output.txt");
    REP(i,d)fout<<ans[i]<<"\n";
    fout.close();
    return;
  }
  REP(i,d)cout<<ans[i]<<"\n";
  return;
}

int score(){
  int res=0;
  memset(tlast,-1,sizeof(tlast));
  REP(day,d){
    res+=S[day][ans[day]-1];
    tlast[ans[day]-1]=day;
    REP(i,26)res-=c[i]*(day-tlast[i]);
  }
  return res;
}

signed main(){
  memset(last,-1,sizeof(last));
  cin>>d;
  REP(i,26)cin>>c[i];
  REP(i,d)REP(j,26)cin>>s[i][j];
  REP(i,d)REP(j,26)S[i][j]=s[i][j];
  REP(j,26){
    int now=-INF;
    for(int i=364;i>=0;i--){
      if(now>15000)s[i][j]-=(now-15000)/10;
      if(now<s[i][j])now=s[i][j];
      now-=c[j];
    }
  }
  REP(day,d){
    int Sc=-INF,now;
    if(day<d-1){
      REP(i,26){
        REP(j,26){
          if(i==j)continue;
          int tmp=s[day][i]+s[day+1][j];
          REP(k,26){
            if(i!=k&&j!=k)tmp-=c[k]*(day-last[k]+day+1-last[k]);
            if(i==k)tmp-=c[k];
            if(j==k)tmp-=c[k]*(day-last[k]);
          }
          if(Sc<tmp)Sc=tmp,now=i;
        }
      }
      ans[day]=now+1;
      last[now]=day;
    }
    else{
      REP(i,26){
        ans[day]=i+1;
        int R=score();
        if(Sc<R)Sc=R,now=i+1;
        else ans[day]=now;
      }
    }
  }/*
  REP(day,d){
    vector<int> minus(26);
    REP(j,26)minus[j]=c[j]*(day-last[j]);
    int A=-INF,idx=0;
    REP(j,26){
      int tmp=s[day][j]+minus[j];
      if(A<tmp)A=tmp,idx=j;
    }
    ans[day]=idx+1;
    last[idx]=day;
  }
  */
  /*
  REP(_,480){
    int day1=rand()%365,day2=rand()%365;
    if(day1==day2)day2++;if(day2==365)day2=0;
    int Sc=-INF,now1=ans[day1],now2=ans[day2];
    REP(i,26){
      REP(j,26){
        ans[day1]=i+1;
        ans[day2]=j+1;
        int R=score();
        if(Sc<R)Sc=R,now1=i+1,now2=j+1;
        else ans[day1]=now1,ans[day2]=now2;
      }
    }
  }
  */
  /*
  REP(_,1000){
    int day1=_%360;
    int now[5],Sc=-INF;
    vector<int> v(5);
    REP(i,5)v[i]=ans[day1+i];
    sort(v.begin(),v.end());
    do{
      REP(i,5)ans[day1+i]=v[i];
      int R=score();
      if(Sc<R){
        REP(i,5)now[i]=v[i];
        Sc=R;
      }
      else REP(i,5)ans[day1+i]=now[i];
    }while(next_permutation(v.begin(),v.end()));
  }
  */
    REP(_,20000){
      int day1=rand()%360;
      int day2=day1+rand()%4+1;
      int R=score();
      swap(ans[day1],ans[day2]);
      if(R>score())swap(ans[day1],ans[day2]);
    }

  FIN(0);
}


Measured memory_bytes: 3708
//#pragma GCC target("avx2")
#pragma GCC optimize("O3")
//#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
#include <prettyprint.hpp>
#define debug(...)  cerr << "[" << #__VA_ARGS__ << "]: ", d_err(__VA_ARGS__);
#else
#define debug(...) 83;
#endif

void d_err() {
    cerr << endl;
}

template <typename H, typename... T>
void d_err(H h, T... t) {
    cerr << h << " ";
    d_err(t...);
}

template <typename T>
void print(T x) {
    cout << x << "\n";
}

#define ALL(x) (x).begin(), (x).end()
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define REVFOR(i, m, n) for (int i = (n - 1); i >= (m); --i)
#define REP(i, n) FOR(i, 0, n)
#define REVREP(i, n) REVFOR(i, 0, n)
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define bcnt __builtin_popcountll

typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<ll,ll> Pll;
typedef pair<int,int> Pin;

ll INF = 1e16;
int inf = 1e9;
ll MOD = 1e9+7;

int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    
    ll n, x, m;
    cin >> n >> x >> m;

    vi v(m);
    for(ll i = 0; i < m; i++) {
        v[i] = i * i % m;
    }

    vll ord;
    set<ll> idx;
    ll c = x;
    ll last;
    while(1) {
        if (idx.count(c) > 0) {
            last = c;
            break;
        }

        idx.insert(c);
        ord.pb(c);
        c = c * c % m;
    }

    ll ans = 0;

    int i = 0;
    for(; i < ord.size(); ++i) {
        if (ord[i] == last) {
            break;
        }
        ans += ord[i];
    }

    n -= i;

    ll len = ord.size() - i;
    ll p_sum = accumulate(ord.begin() + i, ord.end(), 0LL);

    ans += n / len * p_sum;

    FOR(j, i, i + n % len) {
        ans += ord[j];
    }

    print(ans);
}


Measured memory_bytes: 6324
#include<bits/stdc++.h>
using namespace std;
int a[60],ans;
bool pd(int x,int y){return x>y;}
int main()
{
	int n,k;
	cin>>n>>k;
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	sort(a+1,a+n+1,pd);
	for(int i=1;i<=k;i++)
		ans+=a[i];
	cout<<ans;
	return 0;
}

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

int main() {
  int n;
  cin >> n;
  vector<int> a(n);
  rep(i, n) cin >> a[i];
  vector<int> dp(100001, 0);
  rep(i, n) {
    ++dp[a[i]];
    if (a[i] > 0) ++dp[a[i] - 1];
    ++dp[a[i] + 1];
  }
  int ans = 0;
  rep(x, 100001) ans = max(ans, dp[x]);
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 3972
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int k = scan.nextInt();
		int[] x = new int[n];
		int move = 0;
		int i = 0;
		for(i = 0; i < n; i++) {
			x[i] = scan.nextInt();
			int x_k = x[i] - k;
			if(x_k < 0) {
				x_k = x_k * (-1);
			}
			if(x_k >= x[i]) {
				move = move + (2 * x[i]);
			} else {
				move = move + (2 * x_k);
			}
		}
		System.out.println(move);
	}
}

Measured memory_bytes: 21840
package main

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

var sc = bufio.NewScanner(os.Stdin)

func Scan() string {
	sc.Scan()
	return sc.Text()
}
func iScan() int {
	n, _ := strconv.Atoi(Scan())
	return n
}
func fScan() float64 {
	n, _ := strconv.ParseFloat(Scan(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func SScan(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scan()
	}
	return a
}
func iSScan(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = iScan()
	}
	return a
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func sum(a []int) int {
	x := 0
	for _, v := range a {
		x += v
	}
	return x
}
func fSum(a []float64) float64 {
	x := 0.
	for _, v := range a {
		x += v
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	s := Scan()
	a, ab, abc, p := 0, 0, 0, 1
	for _, r := range s {
		if string(r) == "A" {
			a += p
			a %= mod
		} else if string(r) == "B" {
			ab += a
			ab %= mod
		} else if string(r) == "C" {
			abc += ab
			abc %= mod
		} else {
			abc = (abc*3 + ab) % mod
			ab = (ab*3 + a) % mod
			a = (a*3 + p) % mod
			p *= 3
			p %= mod
		}
	}
	fmt.Println(abc)
}


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

#define ll long long
#define fornum(A,B,C) for(A=B;A<C;A++)
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>

using namespace std;

/////////////////////////////////////////////////////
ll N,K;
pll abv[101010];
priority_queue<ll> pq;
ll i,j,k,ans;
int main(){
    scanf("%lld%lld", &N,&K);
    fornum(i,0,N){
        ll A, B;
        scanf("%lld%lld", &A,&B);
        abv[i] = {A, B};
    }
    sort(abv, abv + N);
    j = 0;
    fornum(i,0,K){
        while(j<N&&abv[j].first==i+1){
            pq.push(abv[j].second);
            j++;
        }
        if(pq.empty())
            continue;
        ans += pq.top();
        pq.pop();
    }
    printf("%lld", ans);

    j = 0;
}

Measured memory_bytes: 2936
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 05:38:56 2019

@author: shinjisu
"""


# ABC 200点問題
import math


def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def zeros(n): return [0]*n


def dmp(x):
    global debug
    if debug:
        print(x)


debug = True


def getIntLines(n): return [int(input()) for i in range(n)]


def getIntMat(n):
    mat = []
    for i in range(n):
        mat.append(getIntList())
    return mat


def zeros2(n, m): return [zeros(m)]*n


def prob095():
    X = getIntList()
    K = getInt()
    dmp((X, K))
    total = sum(X) - max(X) + max(X)*2**K
    return total


debug = False
print(prob095())


Measured memory_bytes: 3316
#include <iostream>
#include <iomanip>
#include <utility>
#include <cmath>
#include <random>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;

#define rep(i,n) for(int i = 0; i<n; ++i)
#define REP(i,n) for(int i = 1; i<=n; ++i)
#define all(x) begin(x),end(x)
#define show(obj) {for(auto x:obj)printf("[num:cnt]=[%d,%d]\n",x.first,x.second);}
#define line "----------"
typedef long long ll;
typedef pair<int,int> ip;
typedef pair<ll,ll> lp;
const int inf = 1001001000;
const ll INF = 1LL<<60;
const int MOD = (int)1e9 + 7;

int main(){
	int N,M; cin>>N>>M;
	map<int,int> card;
	rep(i,N){
		int t; cin>>t;
		++card[t];
	}
	rep(i,M){
		int b,c;
		cin>>b>>c;
		for(auto x: card){
			if(x.first >= c)break;
			// cout<<line<<endl;
			// cout<<b<<' '<<c<<endl;
			// show(card);
			if(x.second > b){
				card[x.first] -= b; 
				card[c] += b;
				break;
			}
			card[c] += x.second;
			b -= x.second;
			card.erase(x.first);
			// cout<<line<<endl;
		}
	}
	ll ans = 0LL;
	for(auto x:card){
		// cout<<x.first<<endl;
		ans += (ll)x.first * x.second;
	}
	cout<<ans<<endl;
	return 0;
}

Measured memory_bytes: 4992