akhauriyash/Code-Regression huggingface dataset:
def main():
    while True:
        # minute,team,problem,record
        M,T,P,R = map(int, input().split(" "))
        if M == 0: break

        # [チーム1→[問題1,問題2...],チーム2→[...]...]
        data = [[0 for i in range(P)] for j in range(T)]
        # [正答数,所要合計時間]
        res = [[0, 0] for j in range(T)]
        for item in range(T):
            res[item].insert(0, item + 1)
        
        for i in range(R):
            # minute,team,problem,judge
            m,t,p,j = map(int, input().split(" "))

            # 0秒での正解を見分けるための端数1
            if j == 0: data[t - 1][p - 1] = -(data[t - 1][p - 1]) * 20 + m + 1
            else: data[t - 1][p - 1] -= 1
            
        for i in range(len(data)):
            for item in data[i]:
                if item < 0: continue
                if item != 0:
                    res[i][1] += 1
                    res[i][2] -= (item - 1)

        res = sorted(res, key = lambda x:(x[1], x[2], x[0]), reverse = True)
        
        output(res)

def output(listt):
    print(str(listt[0][0]), end = "")
    for i in range(1, len(listt)):
        if listt[i][1] == listt[i - 1][1] and listt[i][2] == listt[i - 1][2]:
            print("=" + str(listt[i][0]), end = "")
        else: print("," + str(listt[i][0]), end = "")
    print("")
main()



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

int main() {
  int N;
  cin >> N;
  vector<string> data(N);
  for (int i = 0; i < N; i++) {
    cin >> data.at(i);
  }
  map<string, int> g;
  for (int i = 0; i < N; i++) {
    if (g.count(data.at(i))) {
      g[data.at(i)] = 1;
    }
    else {
      g[data.at(i)]++;
    }
  }
  cout << g.size() << endl;
        
}


Measured memory_bytes: 25172
#include<stdio.h>

int main() {
	int t;
	int sum = 0;
	for (int i = 0; i < 4; ++i) {
		scanf("%d", &t);
		sum += t;
	}

	int ansm, anss;
	ansm = sum / 60;
	sum = sum % 60;
	anss = sum;

	printf("%d\n%d\n", ansm, anss);

	return 0;
}

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

int main(){
    int n,m;
    bool ok=false;
    cin >> n >> m;
    map<int,int> Map;
    for(int i=0;i<m;i++){
        int a,b;
        cin >> a >> b;
        if(b==n){
            Map[a]++;
            //cout << Map[a] << endl;
            if(Map[a]==2){ok=true;}
            }
        if(a==1){
            Map[b]++;
            //cout << Map[b] << endl;
            if(Map[b]==2){ok=true;}
        }
    }
    if(ok)cout << "POSSIBLE" << endl;
    else cout << "IMPOSSIBLE" << endl;
    return 0;
}

Measured memory_bytes: 9600
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  string A;
  cin >> A;
  if((A[0]==A[1] && A[1]==A[2]) || (A[1]==A[2] && A[2]==A[3])){
    cout << "Yes" << endl;
  }
  else cout << "No" << endl;
}

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

using namespace std;

int main() {
 int N;
cin>>N;
if(N==1) cout<<"Hello World"<<endl;
else if (N==2) {
      int A,B;
       cin>>A>>B;
          cout<<A+B<<endl;
       }
}

Measured memory_bytes: 256
/* ex3_4
   moka223711 */

// 1から9までの2つの数の積として表せるような数であるかを判定する

#include <stdio.h>

int main(void){
	int num, dis = 0; // discriminant
	scanf("%d", &num);

	// numを1から9で割って、余りが0かつ商が9以下になっているものを探す
	// 割れるものが見つかったらdisを1に変える
	for(int i = 1; i <= 9; i++){
		if(num % i == 0 && num / i <= 9){
			dis = 1;
			break;
		}
	}
	
	// 上のfor文で1から9で割り切れるものが見つかったときdis==1となっているため
	// if文が実行される、なかったときはelse文の実行
	if(dis){
		printf("Yes");
	}
	else{
		printf("No");
	}
  
	return 0;
}


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

using namespace std;

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

const int N = 2e5 + 5;

int n;
char s[N];

int main() {
  scanf("%s", s + 1);
  n = strlen(s + 1);
  int cnt = 0;
  ll ans = 0;
  for(int i = 1; i <= n - 2; i++) {
    if(s[i] == 'A' and s[i + 1] == 'B' and s[i + 2] == 'C') {
      ans += cnt + 1;
      s[i + 2] = 'A';
      i++;
    }
    else if(s[i] == 'A')
      cnt++;
    else
      cnt = 0;
  }
  printf("%lld\n", ans);
  return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rng(i, a, b) for (int i = int(a); i < int(b); i++)
#define rep(i, b) rng(i, 0, b)
#define gnr(i, a, b) for (int i = int(b) - 1; i >= int(a); i--)
#define per(i, b) gnr(i, 0, b)
#define bg begin()
#define ed end()
#define all(x) x.bg, x.ed
#define vi vector<int>
template <class t, class u>
bool chmax(t &a, u b)
{
    if (a < b)
    {
        a = b;
        return true;
    }
    return false;
}
template <class t, class u>
bool chmin(t &a, u b)
{
    if (b < a)
    {
        a = b;
        return true;
    }
    return false;
}

signed main()
{
    map<int, int> d;
    map<int, int> t;
    int n, m;
    cin >> n;
    rep(i, n)
    {
        int input;
        cin >> input;
        d[input]++;
    }
    cin >> m;
    rep(i, m)
    {
        int input;
        cin >> input;
        t[input]++;
    }
    for (auto i : t)
    {
        if (i.second > d[i.first])
        {
            cout << "NO" << endl;
            return 0;
        }
    }
    cout << "YES" << endl;
    return 0;
}

Measured memory_bytes: 22288
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) {
		SC sc = new SC(System.in);
		String s=sc.next();
		for(int i=0; i<3; i++) {
			if(s.charAt(i)==s.charAt(i+1)) {
				pl("Bad");
				System.exit(0);
			}
		}
		pl("Good");
	}
	static class SC {
		private BufferedReader reader = null;
		private StringTokenizer tokenizer = null;
		public SC(InputStream in) {
			reader = new BufferedReader(new InputStreamReader(in));
		}
		public String next() {
			if (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(reader.readLine());
				} catch (IOException e) {
					throw new UncheckedIOException(e);
				}
			}
			return tokenizer.nextToken();
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
		public long nextLong() {
			return Long.parseLong(next());
		}
		public double nextDouble() {
			return Double.parseDouble(next());
		}
		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				throw new UncheckedIOException(e);
			}
		}
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
	public static void pl() {
		System.out.println();
	}
	public static void p(Object o) {
		System.out.print(o);
	}
}

Measured memory_bytes: 21332
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

    N, L, T = map(int, input().split())
    M, T = divmod(T, L)
    X = []
    W = []
    for _ in range(N):
        x, w = map(int, input().split())
        X.append(x)
        W.append(w)

    if N == 1:
        if W[0] == 1:
            print((X[0] + T)%L)
        else:
            print((X[0] - T)%L)
        exit()

    Y = []
    for i in range(N):
        if W[i] == 1:
            Y.append(((X[i] + T)%L, 1))
        else:
            Y.append(((X[i] - T)%L, 2))
    Y.sort(key=lambda p: p[0])

    if W[0] == 1:
        y0 = (X[0] + T)%L
        for i in range(N):
            if Y[i][0] == y0:
                i0 = i
                break
        S = 0
        i = 0
        idx = (M * W.count(2) * 2)%N
        while True:
            i = (i+1)%N
            if i:
                S += X[i] - X[i-1]
            else:
                S += L - (X[-1] - X[0])
            if S >= T*2:
                break
            if W[i] == 2:
                idx = (idx+1)%N
        ans = [0] * N
        for i in range(N):
            ans[(idx+i)%N] = Y[(i0+i)%N][0]
    else:
        y0 = (X[0] - T) % L
        for i in range(N-1, -1, -1):
            if Y[i][0] == y0:
                i0 = i
                break
        S = 0
        i = 0
        idx = (-M * W.count(1) * 2)%N
        while True:
            i = (i - 1) % N
            if i != N-1:
                S += X[i+1] - X[i]
            else:
                S += L - (X[-1] - X[0])
            if S >= T * 2:
                break
            if W[i] == 1:
                idx = (idx - 1)%N
        ans = [0] * N
        for i in range(0, -N, -1):
            ans[(idx + i) % N] = Y[(i0+i)%N][0]
    for a in ans:
        print(a)


if __name__ == '__main__':
    main()


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

#define fst first
#define snd second
#define fore(i,a,b) for(int i=a, ThxDem=b; i<ThxDem; ++i)
#define pb push_back
#define ALL(s) s.begin(),s.end()
#define FIN ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define SZ(s) int(s.size())
#define DBG(x) cerr <<#x << " = " << (x) << "\n"

#define SQR(x) ((x) * (x))

#define PI 3.1415926535897932385
#define INF 1000111222
#define eps 1e-7
#define maxN 11

using namespace std;

typedef long long ll;
typedef vector<ll> vll;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef vector<string> vstr;
typedef vector<vll> vvll;
typedef vector<bool> vbool;
typedef vector<pll> vpll;
typedef vector<vpll> vvpll;
typedef vector<vbool> vvbool;

vll ns,dp;
ll n;

ll solve(ll pos){
	ll & d = dp[pos];
	if(d != -1) return d;
	ll v=INF;
	if((pos+1)<n)v = min(v,abs(ns[pos+1]-ns[pos])+solve(pos+1));
	if((pos+2)<n)v = min(v,abs(ns[pos+2]-ns[pos])+solve(pos+2));
	if(pos == (n-1)) v = 0;
	return d = v;
}

int main(){FIN
	
	cin >> n;
	ns.resize(n);
	dp.assign(100010,-1);
	fore(i,0,n)cin >> ns[i];
	
	solve(0);
	
	cout << dp[0] << "\n";

	return 0;
}


Measured memory_bytes: 6528
package main

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

var sc = bufio.NewScanner(os.Stdin)
func scanInt() int {
	sc.Scan()
	a,_ := strconv.Atoi(sc.Text())
	return a
}

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

func main() {
	sc.Split(bufio.ScanWords)
	
	a, b := scanInt(),scanInt()

	c := 1
	ans := 0

	for c < b {
		ans++
		c += a - 1
	}

	fmt.Println(ans)
}


Measured memory_bytes: 640
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    x1, y1, x2, y2 = il()
    dx = x2 - x1
    dy = y2 - y1
    x3 = x2 - dy
    y3 = y2 + dx
    x4 = x3 - dx
    y4 = y3 - dy
    print(x3, y3, x4, y4)


if __name__ == '__main__':
    main()


Measured memory_bytes: 10140
#include<stdio.h>
int main() {
	int N, fx = 0;
	scanf("%d", &N);
	for (int i = 1;N>i;i *= 10) {
		fx += ((N - (N%i))/i) % 10;
	}
	printf("%s", fx==0?"Yes":(N % fx == 0 ? "Yes" : "No"));
}

Measured memory_bytes: 128
#include <iostream>
using namespace std;
int main()
{
	long long a0,b0,c0;
	cin>>a0>>b0>>c0;
	long long a=a0,b=b0,c=c0;
	long long num=0;
	while(1)
	{
		if(a%2==1||b%2==1||c%2==1)
		{
			cout<<num<<endl;
			break;
		}
		long long t1,t2,t3;
		t1=a/2,t2=b/2,t3=c/2;
		a=t2+t3;b=t1+t3;c=t1+t2;
		num++;
		if(a==a0&&b==b0&&c==c0)
		{
			cout<<"-1\n";
			break;
		}
	}
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long int ll;

ll mod=1e9+7;

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n; cin >> n;
    string s; cin >> s;
    for(int i=0;i<2*n;i++){
        if(i%2==0){
            if(s[i]=='B')s[i]='W';
            else s[i]='B';
        }
    }
    ll ans=1;
    ll now=0;
    for(int i=0;i<2*n;i++){
        if(s[i]=='W')now++;
        else{
            if(now==0){
                cout << 0 << endl;
                return 0;
            }
            (ans*=now)%=mod;
            now--;
        }
    }
    if(now){
        cout << 0 << endl;
        return 0;
    }
    for(ll i=1;i<=n;i++){
        (ans*=i)%=mod;
    }
    cout << ans << endl;
}


Measured memory_bytes: 720
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;

int main(){
  int a, b, C;
  double S, L, h;
  double PI=acos(-1);

  cin>>a>>b>>C;
  S=a*b*sin(C*PI/180.0)/2;
  L=a+b+sqrt(a*a+b*b-2*a*b*cos(C*PI/180.0));
  h=b*sin(C*PI/180.0);

  printf("%f\n%f\n%f\n", S, L, h);
  return 0;
}

Measured memory_bytes: 3372
import sys
import math

s = input()
Q = int(input())
query = []
[query.append(input().split()) for _ in range(Q)]

inversion = -1

if len(s) >= 3:
    head = s[0]
    tail = s[-1]
    body = s[1:-1]
    for i in range(Q):
        if query[i][0] == "1":
            inversion *= -1
            continue

        c = str(query[i][2])
        if query[i][1] == "1" and inversion == -1:
            head = c + head
        elif query[i][1] == "1" and inversion == 1:
            tail = tail + c
        elif query[i][1] == "2" and inversion == -1:
            tail = tail + c
        else:
            head = c + head
        
    if inversion == -1:
        print(head + body + tail)
    else:
        print(tail[::-1] + body[::-1] + head[::-1])

else:
        for i in range(Q):
            if query[i][0] == "1":
                inversion *= -1
                continue

            c = str(query[i][2])
            if query[i][1] == "1" and inversion == -1:
                s = c + s
            elif query[i][1] == "1" and inversion == 1:
                s = s + c
            elif query[i][1] == "2" and inversion == -1:
                s = s + c
            else:
                s = c + s
        
        if inversion == -1 :
            print(s)
        else:
            print(s[::-1])

Measured memory_bytes: 41820
ab = gets.split(" ").map(&:to_i)
s = gets.chomp
hifnNum = 0

if s.length!=(ab[0]+ab[1]+1)
  puts "No"
  exit
end

(s.length).times do |i|
  if s[i] =="-"
    hifnNum = hifnNum+1
  end
end

if hifnNum !=1
  puts "No"
  exit
end


if s[(ab[0]+1)-1] != "-"
  puts "No"
  exit
end

puts "Yes" if (s.length - ab[0] -1) == ab[1] ;


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

int main() {
  int a,b,c,d;
  cin >> a >> b >> c >> d;
  if ((a + b) > (c + d)) {
    cout << "Left" << endl;
  } else if ((a + b) < (c + d)) {
    cout << "Right" << endl;
  } else {
    cout << "Balanced" << endl;
  }
}


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


int main(void)
{
	int N;
	cin >> N;
	int ans = 0;

	for (int i = 1; i<= N; i++) {
		unsigned int a;
		cin >> a;
		while (((a & 0x1) == 0) && (a > 0)) {
			ans++;
			a = (a >> 1);
		}
	}

	cout << ans << endl;

	return 0;
}


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

namespace _0098
{
    public class Program

    {
        public static void Main(string[] args)
        {
            int n = RInt();
            int[,] cSum = new int[n + 1, n + 1];

            //累積和の作成
            for (int i = 0 ; i < n ; i++)
            {
                int[] items = RIntAr();
                for (int j = 0 ; j < n ; j++)
                {
                    cSum[i + 1, j + 1] = cSum[i, j + 1] + cSum[i + 1, j] - cSum[i, j] + items[j];
                }
            }

            int max = int.MinValue;
            //部分和のチェック
            for (int xs = 0 ; xs < n ; xs++)
            {
                for (int xt = xs + 1 ; xt < n + 1 ; xt++)
                {
                    for (int ys = 0 ; ys < n ; ys++)
                    {
                        for (int yt = ys + 1 ; yt < n + 1 ; yt++)
                        {
                            max = Math.Max(cSum[yt, xt] - cSum[yt, xs] - cSum[ys, xt] + cSum[ys, xs], max);
                        }
                    }
                }
            }
            Console.WriteLine(max);
        }

        static string RSt() { return Console.ReadLine(); }
        static int RInt() { return int.Parse(Console.ReadLine().Trim()); }
        static long RLong() { return long.Parse(Console.ReadLine().Trim()); }
        static double RDouble() { return double.Parse(Console.ReadLine()); }
        static string[] RStAr(char sep = ' ') { return Console.ReadLine().Trim().Split(sep); }
        static int[] RIntAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => int.Parse(e)); }
        static long[] RLongAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => long.Parse(e)); }
        static double[] RDoubleAr(char sep = ' ') { return Array.ConvertAll(Console.ReadLine().Trim().Split(sep), e => double.Parse(e)); }
        static string WAr<T>(IEnumerable<T> array, string sep = " ") { return string.Join(sep, array.Select(x => x.ToString()).ToArray()); }
    }

}



Measured memory_bytes: 15996
import java.util.Arrays;
import java.util.Collections;
import java.util.Objects;
import java.util.Scanner;

class Pair implements Comparable<Pair> {
    int pos;
    long value;
    Pair(int pos, long value) {
        this.pos = pos;
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Pair pair = (Pair) o;
        return pos == pair.pos &&
                value == pair.value;
    }

    @Override
    public int hashCode() {
        return Objects.hash(pos, value);
    }

    @Override
    public int compareTo(Pair o) {
        return Long.compare(this.value, o.value);
    }
}
public class Main {
    public static void main(String [] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        Pair [] a = new Pair[n];
        for (int i = 0; i < n; ++i) {
            a[i] = new Pair(i, scanner.nextLong());
        }
        Arrays.sort(a, Collections.reverseOrder());
        long[][] dp = new long[n + 1][n + 1];
        dp[1][0] = a[0].value * a[0].pos;
        dp[0][1] = a[0].value * (n - 1 - a[0].pos);
        for (int i = 1; i < n; ++i) {
            for (int left = 0; left <= i; ++left) {
                int right = i - left;
                dp[left + 1][right] = Math.max(
                        dp[left + 1][right],
                        dp[left][right] + a[i].value * Math.abs(a[i].pos - left)
                );
                dp[left][right + 1] = Math.max(
                        dp[left][right + 1],
                        dp[left][right] + a[i].value * Math.abs(a[i].pos - (n - right - 1))
                );
            }
        }
        long ans = 0;
        for (int left = 0; left <= n; ++left) {
            ans = Math.max(ans, dp[left][n - left]);
        }
        System.out.print(ans);
    }
}


Measured memory_bytes: 84804
import java.util.Arrays;
import java.util.HashMap;
import java.util.Random;
import java.util.Scanner;

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

    int N = scanner.nextInt();
    char[] s = scanner.next().toCharArray();
    int[] M = {999_999_937, 1_000_000_007};
    int B = new Random().nextInt(999_999_937);
    int left = 0;
    int right = N / 2 + 1;
    while (right - left > 1) {
      int mid = (left + right) / 2;
      if (possible(s, mid, N, B, M)) left = mid;
      else right = mid;
    }
    System.out.println(left);
  }

  private static boolean possible(char[] s, int K, int N, int B, int[] M) {
    long[] bn = new long[M.length];
    for (int i = 0; i < M.length; i++) {
      bn[i] = 1;
      for (int j = 0; j < K - 1; j++) {
        bn[i] *= B;
        bn[i] %= M[i];
      }
    }

    HashMap<Tuple, Integer> occurrences = new HashMap<>();
    long[] hash = new long[M.length];
    for (int i = 0; i < M.length; i++) {
      hash[i] = hash(s, K, B, M[i]);
    }
    occurrences.put(new Tuple(hash), 0);
    for (int i = 1; i <= N - K; i++) {
      for (int j = 0; j < M.length; j++) {
        hash[j] -= s[i - 1] * bn[j] % M[j];
        if (hash[j] < 0) hash[j] += M[j];
        hash[j] *= B;
        hash[j] %= M[j];
        hash[j] += s[i + K - 1];
        if (hash[j] >= M[j]) hash[j] -= M[j];
      }
      Tuple key = new Tuple(hash);
      if (occurrences.containsKey(key)) {
        if (occurrences.get(key) + K <= i) return true;
      }
      else occurrences.put(key, i);
    }
    return false;
  }

  private static long hash(char[] s, int len, int B, int M) {
    if (s.length < len) throw new IllegalArgumentException("len must be equal to or more than s.length: len=" + len + ", s.length=" + s.length);
    long hash = 0;
    for (int i = 0; i < len; i++) {
      hash *= B;
      hash %= M;
      hash += s[i];
      if (hash >= M) hash -= M;
    }
    return hash;
  }

  private static class Tuple {
    private final long[] elements;

    private Tuple(long[] elements) {
      this.elements = Arrays.copyOf(elements, elements.length);
    }

    @Override public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      Tuple tuple = (Tuple) o;
      return Arrays.equals(elements, tuple.elements);
    }

    @Override public int hashCode() {
      return Arrays.hashCode(elements);
    }
  }
}


Measured memory_bytes: 31400
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<iomanip>
using namespace std;
typedef long long int ll;
long long int a[100001]={},b[100001]={};
int main()
{
	int n,k;cin>>n>>k;
	int s[100000];
	for(int i=0;i<n;i++)
	{
		cin>>s[i];
	}
	a[1]=s[0];
	b[1]=max(s[0],0);
	for(int i=2;i<=n;i++)
	{
		a[i]=s[i-1]+a[i-1];
		b[i]=max(s[i-1],0)+b[i-1];
	}
	ll ans=0;
	ll sum;
	for(int i=0;i<=n-k;i++)
	{
		sum=a[i+k]-a[i];
		if(sum<0)sum=0;
		sum+=b[i]-b[0];
		sum+=b[n]-b[i+k];
		ans=max(ans,sum);
	}
	cout<<ans<<endl;
	return 0;
}


Measured memory_bytes: 2176
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,nn) for(int i=0;i<nn;i++)
#define MOD 1000000007
typedef long long ll;
template <class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}else{return 0;}}
template <class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}else{return 0;}}
template <class T> inline T GCD(T a,T b){T c;while(b!=0){c=a%b;a=b;b=c;}return a;}
template <class T> inline T LCM(T a,T b){return a*b/GCD(a,b);}


int main(){
  int a,p;
  cin >> a >> p;
  int ans=0;
  ans=(a*3+p)/2;
  cout << ans << endl;
  
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstring>
#include <chrono>
#include <complex>
#define endl "\n"
#define ll long long int
#define vi vector<int>
#define vll vector<ll>
#define vvi vector < vi >
#define pii pair<int,int>
#define pll pair<long long, long long>
#define mod 1000000007
#define inf 1e18L+5
#define all(c) c.begin(),c.end()
#define mp(x,y) make_pair(x,y)
#define mem(a,val) memset(a,val,sizeof(a))
#define eb emplace_back
#define f first
#define s second

#ifdef LOCAL
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
#else
#define eprintf(...) 42
#endif



using namespace std;

void max_self(ll &a, ll b){
    a = max(a, b);
}
void min_self(ll &a, ll b){
    a = min(a, b);
}

int main()
{
    ll N, W;
    cin>>N>>W;
    vector<ll> weight(N), value(N);
    for (ll i = 0; i < N; ++i) {
        cin>>weight[i]>>value[i];
    }
    ll value_sum = 0;
    for(ll x:value){
        value_sum += x;
    }
    vector <ll> dp(value_sum+1, inf);
    dp[0] = 0;
    for (ll item = 0; item < N; ++item) {
        for (ll value_already = value_sum - value[item]; value_already >= 0 ; --value_already) {
            min_self(dp[value_already+value[item]], dp[value_already] + weight[item]);

        }
    }
    ll ans = 0;
    for (ll j = 0; j <= value_sum; ++j) {
        if(dp[j]<=W)
            max_self(ans, j);
    }
    cout<<ans<<endl;


}


Measured memory_bytes: 1024
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static final int INF = 1000000000;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int[][] cost = new int[100][100];
		int[][] time = new int[100][100];
		
		while(true){
			int n = Integer.parseInt(sc.next());
			int m = Integer.parseInt(sc.next());
			if(n == 0 && m == 0){
				break;
			}
			
			for(int i = 0; i < m; i++){
				for(int j = 0; j < m; j++){
					cost[i][j] = INF;
					time[i][j] = INF;
				}
			}
			for(int i = 0; i < n; i++){
				int a = Integer.parseInt(sc.next()) - 1;
				int b = Integer.parseInt(sc.next()) - 1;
				cost[a][b] = Integer.parseInt(sc.next());
				cost[b][a] = cost[a][b];
				time[a][b] = Integer.parseInt(sc.next());
				time[b][a] = time[a][b];
			}
			for(int k = 0; k < m; k++){
				for(int i = 0; i < m; i++){
					for(int j = i + 1; j < m; j++){
						cost[i][j] = Math.min(cost[i][j], cost[i][k] + cost[k][j]);
						cost[j][i] = cost[i][j];
						time[i][j] = Math.min(time[i][j], time[i][k] + time[k][j]);
						time[j][i] = time[i][j];
					}
				}
			}
			int k = sc.nextInt();
			for(int i = 0; i < k; i++){
				int p = Integer.parseInt(sc.next()) - 1;
				int q = Integer.parseInt(sc.next()) - 1;
				int r = Integer.parseInt(sc.next());
				if(r == 0){
					System.out.println(cost[p][q]);
				}else if(r == 1){
					System.out.println(time[p][q]);
				}
			}
		}
		
		sc.close();
	}

}

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

string four(int n){
	if(n==0)return "0";
	string ret;
	while(n){
		ret += (char)(n%4+'0');
		n/=4;
	}
	reverse(ret.begin(),ret.end());
	return ret;
}

int main(){
	int n;
	while(cin >> n && n != -1){
		cout << four(n) << endl;
	}
}

Measured memory_bytes: 0
#import numpy as np
#import functools
#import operator
#from itertools import combinations as comb
#from itertools import combinations_with_replacement as comb_with
#from itertools import permutations as perm
import collections as C

#N = int(input())
N,M= map(int,input().split())
#P = list(map(int,input().split()))

#S= str(input())
#prod = functools.partial(functools.reduce, operator.mul)
#c=np.array(A)
#p=np.prod(A)

num=[0 for x in range(31)]
for i in range(N):

    K = list(map(int,input().split()))
    for j in K[1:]:
        num[j]+=1
c=0
for k in num:
    if k==N:
        c+=1
print(c)


Measured memory_bytes: 3316
/*																													   
 Templatka c++ Kacper Fis																							   																											   //
*/																													  
																								   
#include <bits/stdc++.h>																							   
																													   
using namespace std; 																								   
																													   
const int INF = 1000000001;																						   
const float PI = 3.14;																								   
typedef long long LL;																								   
																													   
typedef vector<int> vi;																								   
typedef list<int> li;																								   
typedef queue<int> qi; 																								   
typedef pair<int,int> ii; 																							   
typedef map<string,int> msi; //np msi['nazwa'] = 'liczba'															   
typedef vector<ii> vii; //vector par<int>, do tworzenia tablicy dla grafów wagowych #dijkstra #Bellman_Ford			   
typedef priority_queue< ii, vector<ii>, greater<ii> > pq; //kolejka priorytetowa vectorów par(top()=min) #dijkstra	   
																													   																				   
vector<ii>::iterator iter;																							   
																													   																				   
#define print_list(x) for(it = (x).begin(); it != (x).end(); it++) {cout << *it << " ";}							   
#define print_vector(x) for(it2 = (x).begin(); it2 != (x).end(); it2++) {cout << *it2 << " ";}						   
#define search_list(x) for(it = (x).begin(); it != (x).end(); it++)													   
#define search_vector(x) for(it2 = (x).begin(); it2 != (x).end(); it2++);											   
#define pb(x) push_back(x) 																							   
#define pf(x) push_front(x)																							   
#define mp(x, y) make_pair(x, y)                                                                                       
///////////////////////////////////////////////GLOBAL DEFINITIONS////////////////////////////////////////////////////////


///////////////////////////////////////////////////FUNCTIONS/////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////MAIN////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])																					 
{ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);                  												       
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    
	unsigned long long n, a, b;
	cin >> n >> a >> b;
	unsigned long long ans;
	
	if((a % 2 == 1) && (b % 2 == 1)){
		cout << (b - a) / 2 << endl;
		return 0;
	}
	else if((a % 2 == 0) && (b % 2 == 0)){
		cout << (b - a) / 2 << endl;
		return 0;
	}
	else{
		unsigned long long mini = min(a - 1, n - b);
		ans = mini + 1 + ((b - a - 1)/2);
		cout << ans << endl;
	}

	





	
	
	
	return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define rep1(i,n) for (int i = 1; i <= (n); ++i)

using namespace std;
using ll = long long;
using P = pair<int,int>;
using ull= unsigned long long;
const ll K_MAX=1e5+5;
const int INF=1e9;

int main(){
  int n;
  cin>>n;
  vector<P> st(n);

  rep(i,n){
    int x,l;
    cin>>x>>l;
    st[i].second=x-l;
    st[i].first=x+l; //sortのため．
  }
  sort(st.begin(),st.end());

  int t_min=-INF;
  int Nrobot=0;

  rep(i,n){
    if(st[i].second>=t_min){//追加
      t_min=max(t_min, st[i].first);
      Nrobot++;
      //cout<<st[i].second<<" "<<st[i].first;
    }

  }
  cout<<Nrobot<<endl;
}


Measured memory_bytes: 1152
n = int(input())
s = input()
l = [[],[],[],[],[],[],[],[],[],[]]

for i in range(n):
    l[int(s[i])].append(i)

def hantei(i):
    p = -1
    q = -1

    a = i // 100
    b = i // 10 - a * 10
    c = i - a * 100 - b * 10

    if len(l[a]) == 0:
        return 0
    else:
        p = l[a][0]

    if len(l[b]) == 0:
        return 0
    else:
        for j in range(len(l[b])):
            if l[b][j] > p:
                q = l[b][j]
                break
        if q == -1:
            return 0

    if len(l[c]) == 0:
        return 0
    else:
        for j in range(len(l[c])):
            if l[c][j] > q:
                return 1
    return 0

ans = 0

for i in range(1000):
    ans += hantei(i)

print(ans)

Measured memory_bytes: 39920
#include <bits/stdc++.h>
#define rep(i,n)for(int i=0;i<(n);i++)
using namespace std;
typedef pair<int,int>P;
 
vector<int>E[100000];
int s[100000],t[100000];
int dep[100000],low[100000],k;
bool used[100000];
vector<P>V;
 
void dfs(int v,int p,int d){
    used[v]=true;
    low[v]=dep[v]=d;
    for(auto u:E[v]){
        if(!used[u]){
            dfs(u,v,d+1);
            low[v]=min(low[v],low[u]);
            if(dep[v]<low[u])V.push_back(P(min(u,v),max(u,v)));
        }
        else if(p!=u){
            low[v]=min(low[v],dep[u]);
        }
    }
}
int main(){
    int v,e;scanf("%d%d",&v,&e);
    rep(i,e){
        scanf("%d%d",&s[i],&t[i]);
        E[s[i]].push_back(t[i]);
        E[t[i]].push_back(s[i]);
    }
    dfs(0,-1,0);
    sort(V.begin(),V.end());
    for(auto p:V){
        cout<<p.first<<' '<<p.second<<endl;
    }
}


Measured memory_bytes: 7732
#include <iostream>

using namespace std;

int user[100000];

void init(int n) {
    fill_n(user, n, -1);
}

int root(int s) {
    if (user[s] < 0)
        return s;
    else
        return user[s] = root(user[s]);
}

void unite(int s, int t) {
    int rs = root(s);
    int rt = root(t);
    if (rs != rt) {
        if (user[rs] < user[rt])
            swap(rs, rt);
        user[rs] += user[rt];
        user[rt] = rs;
    }
}

bool same(int s, int t) {
    return root(s) == root(t);
}

int main() {
    int n, m, q, s, t, c = 1;
    cin >> n >> m;
    init(n);
    for (int i = 0; i < m; ++i) {
        cin >> s >> t;
        unite(s, t);
    }
    cin >> q;
    for (int i = 0; i < q; ++i) {
        cin >> s >> t;
        if (same(s, t))
            cout << "yes" << endl;
        else 
            cout << "no" << endl;
    }

    return 0;
}


Measured memory_bytes: 4088
#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef pair<ll, ll> PP;
#define rep(i, n) for(ll i = 0; i < ll(n); i++)
#define rrep(i, n) for(ll i = n - 1; i > -1; i--)
#define all(v) v.begin(), v.end()
#define pb push_back
#define fi first
#define se second
#define debug(V) rep(i, V.size()) cout << V[i] << " ";
const ll INF = 1LL << 61;
const ll MOD = 1000000007 /*998244353*/;
const ll MAX_N = 500010;
ll a, b, c, d, e, f, h, x, y, z, p, q, m, n, t, r, k, w, l, ans, i, j;
string S, T;
vl A, B;
void solve() {
    n = S.length();
    rep(i, n) {
        if(S[i] == '?')
            S[i] = 'D';
    }
    cout << S << endl;
}
int main() {
    // cout<<fixed<<setprecision(15);
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> S;
    solve();
}

Measured memory_bytes: 3780
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <set>
#include <iomanip>
#include <deque>
#include <stdio.h>
using namespace std;

#define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define RREP(i,n) for(int (i)=(int)(n)-1;i>=0;i--)
#define iREP(i,Itr) for(auto (i)=(Itr).begin();(i)!=(Itr).end();(i)++)
#define REMOVE(Itr,n) (Itr).erase(remove((Itr).begin(),(Itr).end(),n),(Itr).end())
#define PB_VEC(Itr1,Itr2) (Itr1).insert((Itr1).end(),(Itr2).begin(),(Itr2).end())
#define UNIQUE(Itr) sort((Itr).begin(),(Itr).end()); (Itr).erase(unique((Itr).begin(),(Itr).end()),(Itr).end())
#define LBOUND(Itr,val) lower_bound((Itr).begin(),(Itr).end(),(val))
#define UBOUND(Itr,val) upper_bound((Itr).begin(),(Itr).end(),(val))
typedef long long ll;

int h,w;
vector<string> M;

void dfs(int y, int x){
    M[y][x]='.';
    if(y+1<h){
        if(M[y+1][x]=='#'){
            dfs(y+1,x);
            return;
        }
    }
    if(x+1<w){
        if(M[y][x+1]=='#'){
            dfs(y,x+1);
            return;
        }
    }
}

int main(){
    cin>>h>>w;
    M.resize(h);
    REP(i,h)cin>>M[i];
    
    dfs(0,0);
    
    REP(i,h)REP(j,w){
        if(M[i][j]=='#'){
            cout<<"Impossible"<<endl;
            return 0;
        }
    }
    
    cout<<"Possible"<<endl;
    return 0;
}

Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AGC011_A
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ');
            var customers = int.Parse(input[0]);
            var busCapacity = int.Parse(input[1]);
            var angryTime = double.Parse(input[2]);

            var arrivalTime = new List<double>(); //各乗客の到着時刻
            for (int i = 0; i < customers; i++)
            {
                arrivalTime.Add(double.Parse(Console.ReadLine()));
            }

            arrivalTime.Sort();
            var passenger = 0; //バスの現在の乗客
            var needBuses = 0;
            for (int i = 0; i < customers; i++)
            {
                if (i == customers - 1)
                {
                    needBuses++;
                    break;
                }

                if (arrivalTime[i - passenger] + angryTime < arrivalTime[i + 1])
                {
                    passenger = 0;
                    needBuses++;
                }
                else if (arrivalTime[i - passenger] + angryTime >= arrivalTime[i + 1] && arrivalTime[i - passenger] + angryTime <= arrivalTime[i + 1] + angryTime)
                {
                    passenger++;
                    if (passenger == busCapacity)
                    {
                        passenger = 0;
                        needBuses++;
                    }
                }
            }
            Console.WriteLine(needBuses);
        }
    }
}


Measured memory_bytes: 16988
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <map>
#define ll long long
using namespace std;

template <std::uint_fast64_t Modulus> class modint {
  using u64 = std::uint_fast64_t;

public:
  u64 a;

  constexpr modint(const u64 x = 0) noexcept : a(x % Modulus) {}
  constexpr u64 &value() noexcept { return a; }
  constexpr const u64 &value() const noexcept { return a; }
  constexpr modint operator+(const modint rhs) const noexcept {
    return modint(*this) += rhs;
  }
  constexpr modint operator-(const modint rhs) const noexcept {
    return modint(*this) -= rhs;
  }
  constexpr modint operator*(const modint rhs) const noexcept {
    return modint(*this) *= rhs;
  }
  constexpr modint operator/(const modint rhs) const noexcept {
    return modint(*this) /= rhs;
  }
  constexpr modint &operator+=(const modint rhs) noexcept {
    a += rhs.a;
    if (a >= Modulus) {
      a -= Modulus;
    }
    return *this;
  }
  constexpr modint &operator-=(const modint rhs) noexcept {
    if (a < rhs.a) {
      a += Modulus;
    }
    a -= rhs.a;
    return *this;
  }
  constexpr modint &operator*=(const modint rhs) noexcept {
    a = a * rhs.a % Modulus;
    return *this;
  }
  constexpr modint &operator/=(modint rhs) noexcept {
    u64 exp = Modulus - 2;
    while (exp) {
      if (exp % 2) {
        *this *= rhs;
      }
      rhs *= rhs;
      exp /= 2;
    }
    return *this;
  }
};

const ll M=1000000007;

int main(){
    ll n;
    cin>>n;
    vector<ll> a(n);
    for(ll i=0;i<n;i++){
        cin>>a[i];
    }
    modint<M> ans=0;
    for(ll bit=0;bit<60;bit++){
        ll temp=1LL<<bit;
        modint<M> sum0=0;
        modint<M> sum1=0;
        for(int i=0;i<n;i++){
            if(a[i]&temp){
                sum1+=1;
            }else{
                sum0+=1;
            }
        }
        ans+=sum1*sum0*pow(2,bit);
    }
    cout<<ans.a<<endl;
    return 0;
}

Measured memory_bytes: 2688
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <complex>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <climits>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <bitset>
#include <stack>
using namespace std;

#define REP(i,n) for(int i=0;i<(int)n;++i)
#define FOR(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)
#define ALL(c) (c).begin(), (c).end()
typedef long long ll;
typedef pair<int,int> pii;
const int INF = 1<<29;
const double PI = acos(-1);
const double EPS = 1e-8;

int dp[100001][2];
int x[100000];
int n;

int solve(int now, int leg) {
  if (dp[now][leg]>=0) return dp[now][leg];
  if (now==n-1) return 0;
  int res = INF;
  if (leg==0) {
    if (x[now+1] >= x[now]) 
      res = min(res, solve(now+1,1));
    res = min(res, 1+solve(now+1,0));
  } else {
    if (x[now+1] <= x[now]) 
      res = min(res, solve(now+1,0));
    res = min(res, 1+solve(now+1,1));
  }
  return dp[now][leg] = res;
}

int main() {
  string s;
  const int xx[] = {-1,0,1,-1,0,1,-1,0,1};
  while(cin>>s,s!="#") {
    n = s.size();
    REP(i,s.size()) {
      x[i] = xx[s[i]-'1'];      
    }
    memset(dp,-1,sizeof(dp));
    cout << min(solve(0,0),solve(0,1)) << endl;
  }
}

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

public class AtCoderA
{
    static void Main()
    {
        var sc = new Scanner();

        long n = sc.NextLong();
        long[] answers = new long[4];

        for (int i = 0; i < n; i++)
        {
            string s = sc.Next();
            if (s == "AC")
            {
                answers[0]++;
            }
            if (s == "WA")
            {
                answers[1]++;
            }
            if (s == "TLE")
            {
                answers[2]++;
            }
            if (s == "RE")
            {
                answers[3]++;
            }
        }

        Console.WriteLine("AC x " + answers[0]);
        Console.WriteLine("WA x " + answers[1]);
        Console.WriteLine("TLE x " + answers[2]);
        Console.WriteLine("RE x " + answers[3]);
    }

    class Scanner
    {
        private string[] _line;
        private int _index;
        private const char Separator = ' ';

        public Scanner()
        {
            _line = new string[0];
            _index = 0;
        }

        public string Next()
        {
            while (_index >= _line.Length)
            {
                _line = Console.ReadLine().Split(Separator);
                _index = 0;
            }

            return _line[_index++];
        }

        public int NextInt() => int.Parse(Next());
        public long NextLong() => long.Parse(Next());
        public double NextDouble() => double.Parse(Next());
        public decimal NextDecimal() => decimal.Parse(Next());
        public char NextChar() => Next()[0];
        public char[] NextCharArray() => Next().ToCharArray();

        public string[] Array()
        {
            _line = Console.ReadLine().Split(Separator);
            _index = _line.Length;
            return _line;
        }

        public int[] IntArray() => Array().Select(int.Parse).ToArray();
        public long[] LongArray() => Array().Select(long.Parse).ToArray();
        public double[] DoubleArray() => Array().Select(double.Parse).ToArray();
        public decimal[] DecimalArray() => Array().Select(decimal.Parse).ToArray();
    }
}


Measured memory_bytes: 33788
#include<iostream>
using namespace std;
static const int MAX = 100;
static const int INFTY = (1<<21);
static const int WHITE = 0;
static const int GRAY = 1;
static const int BLACK = 2;

int n, M[MAX][MAX];

void dijkstra(){
	int minv;
	int d[MAX], color[MAX];

	for(int i=0;i<n;i++){
		d[i] = INFTY;
		color[i] = WHITE;
	}

	d[0] = 0;
	color[0] = GRAY;
	while(1){
		minv = INFTY;
		int u = -1;
		for(int i=0;i<n;i++){
			if(minv > d[i] && color[i] != BLACK){
				u = i;
				minv = d[i];
			}
		}
		if(u==-1) break;
		color[u] = BLACK;
		for(int v=0;v<n;v++){
			if(color[v] != BLACK && M[u][v] != INFTY){
				if(d[v] > d[u] + M[u][v]){
					d[v] = d[u] + M[u][v];
					color[v] = GRAY;
				}
			}
		}
	}

	for(int i=0;i<n;i++){
		cout << i << " " << (d[i] == INFTY ? -1 : d[i]) << endl;
	}
}

int main(){
	cin >> n;
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			M[i][j] = INFTY;
		}
	}

	int k, c, u, v;
	for(int i=0;i<n;i++){
		cin >> u >> k;
		for(int j=0;j<k;j++){
			cin >> v >> c;
			M[u][v] = c;
		}
	}

	dijkstra();

	return 0;
}

Measured memory_bytes: 3132
#include <stdio.h>

int main(void) {

	int a;
	int b;
	int c;
	int r;

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

	for (int x = a; x <= b; x++){

		if (c % x == 0){
			r++;
		}
}
	printf("%d\n",r);
	return 0;
}


Measured memory_bytes: 2740
local mmi, mma = math.min, math.max
local bls, brs = bit.lshift, bit.rshift
local bxor = bit.bxor

local function grayCode(x)
  return bxor(x, brs(x, 1))
end

-- add_func(idx), rm_func(idx), work_func()
local function grayWalk(size, add_func, rm_func, work_func)
  local prv = 0
  local total = bls(1, size) - 1
  local bpos = {}
  for i = 1, size do
    bpos[bls(1, i - 1)] = i
  end
  work_func()
  for i = 1, total do
    local v = grayCode(i)
    if prv < v then
      prv, v = v, v - prv
      add_func(bpos[v])
    else
      prv, v = v, prv - v
      rm_func(bpos[v])
    end
    work_func()
  end
end

local n = io.read("*n")
local t = {}
local maps = {}
for i = 1, n do
  t[i] = 0
  local a = io.read("*n")
  maps[i] = {}
  for j = 1, a do
    local p, q = io.read("*n", "*n")
    maps[i][p] = q
  end
end

local function add_func(idx)
  t[idx] = 1
end
local function rm_func(idx)
  t[idx] = 0
end
local ret = 0
local function work_func()
  local valid = true
  local c = 0
  for i = 1, n do
    if t[i] == 1 then
      c = c + 1
      for k, v in pairs(maps[i]) do
        if t[k] ~= v then
          valid = false break
        end
      end
    end
    if not valid then break end
  end
  if valid then
    ret = mma(ret, c)
  end
end

grayWalk(n, add_func, rm_func, work_func)
print(ret)


Measured memory_bytes: 2788
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <tuple>
#include <map>
#include <unordered_map>
using namespace std;
typedef long long ll;

int main(int argc, char *argv[])
{
	int q, i;
	string s;
	int ope, option;
	bool rev = false;
	char addchar;
	cin >> s;
	cin >> q;

	for (i = 0; i < q; i++) {
		cin >> ope;
		if (ope == 1) {
			rev = !rev;
		} else if (ope == 2) {
			cin >> option >> addchar;
			if (rev) 
				option = option % 2 + 1;
			if (option == 2)
			    s.push_back(addchar);
			else
				s.insert(s.begin(), addchar);
		}
	}
	if (rev)
		reverse(s.begin(), s.end());

	cout << s << endl;
	return 0;
}


Measured memory_bytes: 900
n, m = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
if n < m:
    x_distance = [x[i + 1] - x[i] for i in range(m - 1)]
    x_distance.sort()
    print(sum(x_distance[:(m-n)]))
else:
    print(0)


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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int a,b;
    cin>>a>>b;
    if(a==1&&b==2)
    {
        cout<<3<<"\n";
    }
    else if(a==2&&b==1)
    {
        cout<<3<<"\n";
    }
    else if(a==1&&b==3)
    {
        cout<<2<<"\n";
    }
    else if(a==3&&b==1)
    {
        cout<<2<<"\n";
    }
    else if(a==3&&b==2)
    {
        cout<<1<<"\n";
    }
    else if(a==2&&b==3)
    {
        cout<<1<<"\n";
    }

}


Measured memory_bytes: 256
//魔法をかける回数を固定(Kに)する。すると、色iのスライムは色i～i-Kのスライムから作れる。
//魔法によるコストは同じなので、この中から最小のものを選べばよい。
//愚直にやると、魔法回数O(N), 色O(N), 最小値O(N)だが、ナイーブに更新すると最小値クエリO(1)になって間に合う。

#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#define int long long
using namespace std;

int n, x;
int a[2000];

signed main() {
	int i, j, k;
	
	cin >> n >> x;
	for (i = 0; i < n; i++) cin >> a[i];
	
	int ans = 11451419198100721;
	int mini[2000];
	for (i = 0; i < n; i++) mini[i] = 1145141919;
	
	//魔法をi回かける
	for (i = 0; i < n; i++) {
		int cst = 0;
		//スライムjを得るためのコスト（魔法コストを除く）
		for (j = 0; j < n; j++) {
			mini[j] = min(a[(j - i + n) % n], mini[j]);
			cst += mini[j];
		}
		ans = min(ans, cst + i * x);
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 256