akhauriyash/Code-Regression huggingface dataset:
# instead of AVLTree
class BITbisect():
    def __init__(self, max):
        self.max = max
        self.data = [0]*(self.max+1)
    
    # 0からiまでの区間和
    # 立っているビットを下から処理
    def query_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s

    # i番目の要素にxを足す
    # 覆ってる区間すべてに足す
    def add(self, i, x):
        while i <= self.max:
            self.data[i] += x
            i += i & -i

    def insert(self, x):
        self.add(x, 1)

    def delete(self, x):
        self.add(x, -1)

    def count(self, x):
        return self.query_sum(x) - self.query_sum(x-1)
    
    def length(self):
        return self.query_sum(self.max)
    
    # 下からc番目(0-indexed)の数
    # O(log(N))
    def search(self, c):
        c += 1
        s = 0
        ind = 0
        l = self.max.bit_length()
        for i in reversed(range(l)):
            if ind + (1<<i) <= self.max:
                if s + self.data[ind+(1<<i)] < c:
                    s += self.data[ind+(1<<i)]
                    ind += (1<<i)
        if ind == self.max:
            return False
        return ind + 1
    
    def bisect_right(self, x):
        return self.query_sum(x)

    def bisect_left(self, x):
        if x == 1:
            return 0
        return self.query_sum(x-1)

    # listみたいに表示
    def display(self):
        print('inside BIT:', end=' ')
        for x in range(1, self.max+1):
            if self.count(x):
                c = self.count(x)
                for _ in range(c):
                    print(x, end=' ')
        print()

import sys
input = sys.stdin.readline
from operator import itemgetter

INF = 10**15

N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

for i in range(N):
    if i%2 == 1:
        a = A[i]
        A[i] = B[i]
        B[i] = a

INDs = []
def dfs(p,L):
    if p == N:
        if len(L) == (N+1)//2:
            INDs.append(L)
        return
    dfs(p+1, L+[p])
    dfs(p+1, L)
    return

dfs(0, [])

ans = INF
for IND in INDs:
    As = []
    Bs = []
    usingA = [False]*N
    for ind in IND:
        usingA[ind] = True
    for ind in range(N):
        if usingA[ind]:
            As.append((A[ind], ind))
        else:
            Bs.append((B[ind], ind))
    As.sort()
    Bs.sort()
    ok = True
    pre = -INF
    Array = [None]*N
    for i in range(N):
        if i%2 == 0:
            if As[i//2][0] < pre:
                ok = False
                break
            Array[As[i//2][1]] = i+1
            pre = As[i//2][0]
        else:
            if Bs[i//2][0] < pre:
                ok = False
                break
            Array[Bs[i//2][1]] = i+1
            pre = Bs[i//2][0]
    if not ok:
        continue
    
    bit = BITbisect(N)
    nowans = 0
    for j, a in enumerate(Array):
        nowans += j - bit.query_sum(a)
        bit.add(a, 1)
    
    if nowans < ans:
        ans = nowans

if ans == INF:
    print(-1)
else:
    print(ans)



Measured memory_bytes: 63836
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e3 + 7;
const ll INF = 1e18;

int a[N], b[N];

int main()
{
	ios::sync_with_stdio(false);

	int n, x;
	cin >> n >> x;
	for (int i=0; i<n; i++)
		cin >> a[i];
	memcpy(b, a, sizeof a);
	ll ans = INF;
	for (int i=0; i<n; i++)
	{
		ll tmp = 0;
		for (int j=0; j<n; j++)
			tmp += a[j];
		ans = min(ans, tmp + 1LL * i * x);
		for (int j=0; j<n; j++)
			a[j] = min(a[j], b[(j + i + 1) % n]);
	}
	cout << ans << "\n";
	return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef vector<vector<int>> Matrix;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define ALL(x) (x).begin(), (x).end()
static const int INF = 2000000000;

const int mod = 1000000000 + 7;

ll factorial(ll x){
  ll ret = 1;
  while (x){
    ret *= x;
    ret %= mod;
    x--;
  }
  return ret;
}

int main(){
  ll n, m;
  cin >> n >> m;
  ll sa = abs(n - m);
  if (sa == 0){
    ll a = factorial(n);
    ll ans = (a * a * 2) % mod;
    cout << ans << endl;
  } else if (sa == 1){
    ll a = factorial(n);
    ll b = factorial(m);
    ll ans = (a * b) % mod;
    cout << ans << endl;
  } else {
    cout << 0 << endl;
  }
  return 0;
}

Measured memory_bytes: 256
#include<cstdio>
#include<vector>
#include<algorithm>


using namespace std;
using vi=vector<int>;
using vvi=vector<vi>;

void div(vi&p, int x)
{
	for(int i=2;i*i<=x;i++)
	{
		if(x%i==0)
		{
			for(;x%i==0;x/=i)
			{
				p[i]++;
			}
		}
	}
	if(x>1) p[x]++;
}


int nCr(int n, int r)
{
	int ret=1;

	if(r>n) return 0;

	for(int i=0;i<r;i++)
	{
		ret=ret*(n-i)/(i+1);
	}
	return ret;
}


int main(void)
{
	int n;

	while(scanf("%d", &n)==1)
	{
		int pn=n+1;
		vi p(pn);

		for(int i=2;i<=n;i++)
		{
			div(p, i);
		}
		sort(p.rbegin(), p.rend());

		int cn=max(75, p.front()+1);
		vi c(cn);
		for(int i=0;i<pn;i++)
		{
			c[p[i]]++;
		}
		for(int i=cn-1;i>0;i--)
		{
			c[i-1]+=c[i];
		}

		int ans=0;

		ans+=nCr(c[4], 2)*(c[2]-c[4])+nCr(c[4], 3)*3;
		ans+=c[14]*(c[4]-c[14])+nCr(c[14], 2)*2;
		ans+=c[24]*(c[2]-c[24])+nCr(c[24], 2)*2;
		ans+=c[74];

		printf("%d\n", ans);
	}
	return 0;
}


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

int main(){

  int N;
  cin >> N;
  if(N == 1){
    cout << 1 << endl;
  } else {
    long int a = 2, b = 1;
    long int c;
    for(int i=2; i<=N; i++){
      c = a + b;
      a = b;
      b = c;
    }
    cout << c << endl;
  }

}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i,n)for(long long i=0;i<(long long)(n);++i)
#define all(a) a.begin(), a.end()
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
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; }
 
const ll MOD=1e9+7;
const ll INF=1e18;
const double pi=acos(-1);
int dx[8] = {1,0,-1,0,1,1,-1,-1};
int dy[8] = {0,1,0,-1,-1,1,1,-1};

const int MAX=510000;
int main(){
  cin.tie(0);
  ios::sync_with_stdio(false); 
  
  char c;
  cin >> c;
  cout << char('a'+c-'a'+1) << endl;
  return 0;
}

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

int main(){
    int N;
    cin>>N;

    vector<int> next_right(N+1);
    for(int i=1;i<=N;i++) cin>>next_right[i];

    int num = 1;
    int res = 0;
    vector<bool> right(N,false);

    for(int i=0;i<=N;i++){
        right[num] = true;
        if(right[2]) break;

        num = next_right[num];
        res++;
    }
    if(right[2]) cout<<res<<"\n";
    else cout<<"-1\n";
}


Measured memory_bytes: 640
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include <map>
#include <iomanip>

using namespace std;


int main() 
{
	int n;
	cin >> n;

	vector<bool> pos(10000);
	for (int i = 0; i < 30; i++)
	{
		for (int j = 0; j < 20; j++)
		{
			int f = i * 4 + j * 7;
			pos[f] = true;
		}
	}
	if (pos[n])
	{
		cout << "Yes\n";
	}
	else
	{
		cout << "No\n";
	}

}

Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <numeric>
#include <cassert>
#include <memory>
#include <stack>
#include <set>
#include <map>
#include <cctype>
#include <climits>
#include <list>
#include <queue>

#define INF 1000000000
#define MOD 1000000007
typedef long long ll;
typedef unsigned long long ull;
using namespace std;

ll fn(ll a, ll b) {
  string A = to_string(a);
  string B = to_string(b);
  return max(A.size(), B.size());
}

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

  ll N; cin>>N;
  ll ans = INF;
  for(ll a=1; a <= sqrt(N); a++) {
    if(N % a == 0) {
      ll b = N / a;
      ans = min(ans, fn(a,b));
    }
  }
  cout << ans << endl;
}



Measured memory_bytes: 256
# アイデア：（これまでどおり）BFS。
# まず頂点に色を塗り，次に，その頂点から出る辺に色を塗ってゆく。
# 頂点に塗られた色及び「その頂点から出る何本目の辺か」によって，その辺に塗る色を決定する。
# 頂点に入ってくるときには，その際に取った辺の色を頂点に塗る。

from collections import deque

N=int(input())
d={} # 辺の両端の頂点→辺の番号を辿れるようにしておく
out=[set() for v in range(N+1)];out[0]=None # 隣接リスト，頂点の番号も問題文どおり1-initial,1~N
for i in range(1,N): # 問題文どおり辺の番号は1-initial,1~N-1
    u,v=map(int,input().split())
    out[u].add(v);out[v].add(u)
    u,v=min(u,v),max(u,v);d[(u,v)]=i
K=max([len(out[v]) for v in range(1,N+1)])
    
vcol=[0 for v in range(N+1)];vcol[0]=None
ecol=[0 for e in range(N)];ecol[0]=None

vr=[False for v in range(N+1)];vr[0]=None

q=deque()
q.append(1);vr[1]=True
vcol[1]=1 # 頂点1を色1で塗る
while q:
    u=q.popleft() # 今いる頂点    
    i=1 # その頂点から塗り始める何本目の辺か(1-initial),1<=i<=K
    for v in out[u]:
        if not vr[v]:
            col=(vcol[u]+i-1)%K+1
            vcol[v]=ecol[d[(min(u,v),max(u,v))]]=col
            vr[v]=True
            q.append(v)
            i+=1

print(K)
for i in range(1,N):
    print(ecol[i])

Measured memory_bytes: 106400
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
//#define ll long long
template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
#define rep(i, n) REP(i, 0, n)
#define rep_rev(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i))
#define ALL(v) v.begin(), v.end()
#define MSG(a) cout << #a << " " << a << endl;
#define REP(i, x, n) for(int i = x; i < n; i++)
#define all(x) (x).begin(),(x).end()
ll t1,t2,t3;
const ll mod = 1000000007;
const int INF = 1e9;
const ll INFLONG = 1e18;

int main(){
  ll n;
  cin >> n;
  vector<ll> ans(n,INFLONG);
  vector<pair<ll,ll>> vec[n];
  ll u;
  ll k;
  rep(_,n){
    cin >> u >> k;
    rep(i,k){
      cin >> t1 >> t2;
      vec[u].emplace_back(make_pair(t2,t1)); //cost , node_num
    }
  }
  priority_queue<pair<ll,ll>> pq;
  ans[0] = 0;
  for(auto itr:vec[0]){
    pq.push(make_pair(-itr.first,itr.second)); //-cost
  }
  pair<ll,ll> pa;
  while(!pq.empty()){
    pa = pq.top();
    pq.pop();
    t1 = -pa.first; //cost
    t2 = pa.second;
    //cout << t1 << " " << t2 << endl;
    if(t1 < ans[t2]){
      ans[t2] = t1;
      for(auto itr:vec[t2]){
        pq.push(make_pair(-t1 - itr.first,itr.second));
      }
    }
  }
  rep(i,n){
    cout << i << " " << ans[i] << endl;
  }
}


Measured memory_bytes: 3208
a = input()
s = a.find(' ')
a+= "."
b = a[s+1:-1]
a= a[0:s]
a=int(a)
b=int(b)
c= int(b/2)
if a>12:
  print(b)
elif a<=12 and a>=6:
  print(c)
else:
  print(0)

Measured memory_bytes: 3064
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

from collections import deque

N = int(readline())
m = map(int,read().split())
A = [None] + list(map(deque,zip(*[m]*(N-1))))

day = 0
rest = N*(N-1)
cand = set(range(1,N+1))
while rest:
    day += 1
    match_player = set()
    for i in cand:
        if not A[i]:
            continue
        if A[A[i][0]][0] == i:
            match_player.add(i)
            match_player.add(A[i][0])
    if not match_player:
        break
    rest -= len(match_player)
    cand.clear()
    for i in match_player:
        cand.add(i)
        A[i].popleft()
        if A[i]:
            cand.add(A[i][0])

answer = day if rest == 0 else -1
print(answer)

Measured memory_bytes: 82844
from collections import deque
from copy import deepcopy
n, k = map(int, input().split())
v = deque(map(int, input().split()))
t = min(n, k)
ans = 0
for a in range(t + 1):
    for b in range(t + 1 - a):
        vv = deepcopy(v)
        belongings = []
        for _ in range(a):
            if vv:
                jewelry = vv.popleft()
                belongings.append(jewelry)
        for _ in range(b):
            if vv:
                jewelry = vv.pop()
                belongings.append(jewelry)
        belongings.sort()
        for i in range(a + b):
            if belongings[i] < 0 and i < (k - a - b):
                belongings[i] = 0
        ans = max(sum(belongings), ans)
print(ans)


Measured memory_bytes: 3444
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <utility>
#include <queue>
#include <algorithm>
#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <climits>
using namespace std;

#define MOD1097 1000000007

#define ll long long
#define pint pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define mpair make_pair
#define pm(first, second) pb(mpair(first, second))
#define SPACE " "
#define fpf first.first
#define fps first.second
#define spf second.first
#define sps second.second

#define all(X) (X).begin(), (X).end()
#define reall(X) (X).rbegin(), (X).rend()
#define divcel(a, b) (((a) + ((b) - 1)) / (b))

int main(){

	int x, y;
	cin >> x >> y;
	int ans = 0;
	if(x == 3)ans += 100000;
	else if(x == 2)ans += 200000;
	else if(x == 1)ans += 300000;
	if(y == 3)ans += 100000;
	else if(y == 2)ans += 200000;
	else if(y == 1)ans += 300000;
	if(x == 1 && y == 1)ans += 400000;
	cout << ans << endl;

	return 0;
}


Measured memory_bytes: 3564
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
#include <math.h>
#include <iomanip>
#include <limits>
#include <list>
#include <queue>
#include <tuple>
#include <map>
using namespace std;
#define MOD (long long int)(1e9+7)
#define ll long long int
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define reps(i,n) for(int i=1; i<=(int)(n); i++)
#define REP(i,n) for(int i=n-1; i>=0; i--)
#define REPS(i,n) for(int i=n; i>0; i--)
#define INF (int)(1123456789)
#define LINF (long long int)(112345678901234567)
#define chmax(a, b) a = (((a)<(b)) ? (b) : (a))
#define chmin(a, b) a = (((a)>(b)) ? (b) : (a))
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define PB push_back
#define SP << " " <<

typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VL;
typedef vector<VL> VLL;

__attribute__((constructor))
void initial(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed <<setprecision(15);
}


int main(void){
	ll H,N;
    cin >> H >> N;
    VL A;
    ll sum = 0;
    rep(i,N){
        ll a;
        cin >> a;
        A.PB(a);
        sum += a;
    }

    string ans = "No";
    if(sum >= H){
        ans = "Yes";
    }

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


Measured memory_bytes: 1400
n = int(input())
l = [0]*4
for i in range(n):
  j = input()
  if j == "AC":
    l[0] += 1
  if j == "WA":
    l[1] += 1
  if j == "TLE":
    l[2] += 1
  if j == "RE":
    l[3] += 1
    
print("AC x", l[0])
print("WA x", l[1])
print("TLE x", l[2])
print("RE x", l[3])

Measured memory_bytes: 69864
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int pd[55][55]={0};
int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    int ans=0;
    for(int i=1;i<=m;i++)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        pd[a][b]=pd[b][a]=1;
    }
    //cout<<pd[1][7]<<endl;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
             int f=0,t=0;
             for(int k=1;k<=n;k++)
            {
                if(pd[j][k]==1)f++;
                if(f==1&&t==0)t=k;
            }
            if(f==1) {pd[j][t]=pd[t][j]=0;ans++;}//printf("j=%d k=%d\n",j,t);}
        }
    }
    printf("%d\n",ans);

}

Measured memory_bytes: 384
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {
	
	public static void main(String[] args) throws IOException {
		MyScanner sc = new MyScanner();
		PrintWriter out = new PrintWriter(System.out);
		int N = sc.nextInt();
		long edges = 0;
		for (int i = 0; i < N - 1; i++) {
			long a = sc.nextLong();
			long b = sc.nextLong();
			long min = Math.min(a, b);
			long max = Math.max(a, b);
			edges += min * (N + 1 - max);
		}
		long ans = 0;
		for (long i = 1; i <= N; i++) {
			ans += (i * (i + 1)) / 2;
		}
		ans -= edges;
		out.println(ans);
		
		out.flush();
	}
	
	static class MyScanner {
		private BufferedReader br;
		private StringTokenizer tokenizer;
		
		public MyScanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		
		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}
		
		public int nextInt() {
			return Integer.parseInt(next());
		}
		
		public long nextLong() {
			return Long.parseLong(next());
		}
	}
}


Measured memory_bytes: 54948
import java.util.*;
public class Main {
	public static void main(String[] args){

		//変数K,A,Bの読み込み
		Scanner sc = new Scanner(System.in);
		int K = sc.nextInt();
		int A = sc.nextInt();
		int B = sc.nextInt();

	//AからBの中にKの倍数があるか1つずつ確かめる
		for(int i = A ; i <= B ; i++) {
		  if(i % K == 0) {
			  System.out.println("OK");
			  return ;  //Kの倍数があれば終わる
		  }
		}

	//Kの倍数がなければこっちの処理
		System.out.println("NG");
	}
}


Measured memory_bytes: 26992
#include<stdio.h>
int main()
  {
    int a,b,c,d;
    scanf("%d %d",&a,&b);
    c=2*b;
    d=a-c;
    if(d>0)
     { 
      printf("%d",d);
      }
    else
      { 
       printf("0");
      }
  return 0;
  }
  
  


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

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define repr(i, n) for(int i = (int)(n); i >= 0; i--)
#define repm(i, m, n) for(int i = (int)(m); i < (int)(n); i++)
#define repmr(i, m, n) for(int i = (int)(n); i >= (int)(m); i--)
#define all(x) (x).begin(),(x).end()
#define inf 2e9

using namespace std;
typedef long long int lli;
typedef long long ll;

int n,q;
vector<vector<int>> tree(200000, vector<int>());

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

    char ans;
    if(a == 'H'){
        if(b == 'H') ans = 'H';
        else ans = 'D';
    }
    else{
        if(b == 'H') ans = 'D';
        else ans = 'H';
    }

    cout << ans << endl;
}


Measured memory_bytes: 4992
def main():
  N = int(input())
  S = [int(input()) for _ in range(N)]
  t = sum(S)
  if t % 10 != 0:
    return t
  S.sort()
  for s in S:
    if s % 10 != 0:
      return t - s
  return 0
print(main())

Measured memory_bytes: 9100
#include<bits/stdc++.h>
using namespace std;
char s[100009];
int main()
{
    scanf("%s",&s);
    int n=strlen(s);

    int k=0;
    for(int i=0;i<n-1;i++)
    {
       if(s[i]!=s[i+1])
       {
           k++;
       }
    }
    cout<<k<<endl;
}


Measured memory_bytes: 384
"""
A+2 < B の場合はビスケットを換金した方が良い
ビスケットを(A-所持数)回叩く
ビスケットを1円に換金する（所持数=0)
ビスケットを1円でB枚購入する（所持数+=B）

それ以下の場合はビスケットを叩いた方が良い
ビスケットをK回叩く

換金する場合、ビスケットを叩いて増やすとは限らない


K:3, A:2, B:3
1. 叩いてビスケット2
2. 換金してビスケット0, 1円
3. 購入してビスケット3


K:3, A:2, B:3
1. 叩いてビスケット2
1. 叩いてビスケット3
1. 叩いてビスケット4

K:3, A:2, B:4
1. 叩いてビスケット2
2. 換金してビスケット0, 1円
3. 購入してビスケット4


K:3, A:2, B:5
1. 叩いてビスケット2
2. 換金してビスケット0, 1円
3. 購入してビスケット5


叩いてもAに到達できないなら交換しない (K < A-1)
レートがマイナスなら交換しない（A+2 >= B）

ビスケットをA枚にする (A-1回叩く）
換金する
購入する（B枚）
B >= A なら換金する
購入する（B枚）

"""

K, A, B = map(int, input().split(" "))

def count_cookie1():
    act = K-2
    act += 1
    cookie = act % A
    yen = act // A
    cookie += yen * B
    return cookie


def count_cookie2():
    global K, A, B
    cookie = 1
    while K > 0:
        print(K, A, cookie)
        if (K < A-cookie) or (A+2 >= B): # 叩いて終わり
            cookie += (K)
            return cookie
        elif (K >= A-cookie+2): # 換金して購入する
            if (A-cookie) > 0:
                K -= (A-cookie)
            else:
                K -= 2

            cookie -= A
            cookie += B
        else: # 叩く
            K -= (A-cookie)
            cookie += (A-cookie)
    return cookie


"""
1. K段階の数直線を定義する
2. A枚までは+1ずつ増加する
3. 以降は2ステップごとに+(B-A)ずつ増加する
    3-1. 増加数がマイナスなら処理をキャンセルして残りK枚追加する
4. 残り1ステップ以下になったら+1ずつ増加する
5. 残りステップが0になったら終了
"""
def count_cookie3():
    global K, A, B
    cookie = 1

    # 2
    if cookie < A:
        K -= (A-cookie)
        cookie = A
    # 3
    n = K // 2
    if (B-A) > 2:
        cookie += (B-A)*n
    else:
        cookie += K
        K = 0
    # 4    
    n = K % 2
    cookie += n
    return cookie


if A+2 < B:
    cookie = count_cookie3()
else:
    cookie = K+1

print(cookie)


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

string s;
stack<char> st;

int main()
{
    cin >> s;
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == 'S')
            st.push('S');
        else
        {
            if (st.size() && st.top() == 'S')
                st.pop();
            else
                st.push('T');
        }
    }
    cout << st.size() << endl;
}

Measured memory_bytes: 644
import java.util.Scanner;

public class Main{
    public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int taro = 0; int hana = 0;
    for(int i=0; i<n; i++) {
    	String t = sc.next();String h = sc.next();
    	if(t.compareTo(h)<0) hana += 3;
    	else if(t.compareTo(h)>0) taro += 3;
    	else {
    		taro++; hana++;
    	}
    }
    System.out.println(taro+" "+hana);
    }
}


Measured memory_bytes: 30204
def resolve():
    A,B,C,D = map(int,input().split())
    N = int(input())*4
    cc = [(8*A,A,1),(4*B,B,2),(2*C,C,4),(D,D,8)]
    cc.sort()
    ans = 0

    for _,cost,vol in cc:
         enable = N//vol
         ans += enable*cost
         N %= vol
    print(ans)
resolve()


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

#define pb push_back
#define eb emplace_back

typedef long long ll;
typedef unsigned long long ull;

using namespace std;




void one_case() {
   int n;
   cin >> n;
   vector<int> t(n + 1), x(n + 1), y(n + 1);
   for (int i = 1; i <= n; ++i) {
       cin >> t[i] >> x[i] >> y[i];
   }
   for (int i = 0; i < n; ++i) {
       auto dx = abs(x[i + 1] - x[i]);
       auto dy = abs(y[i + 1] - y[i]);
       auto dt = t[i + 1] - t[i];
       if (dx + dy > dt) {
           cout << "No\n";
           return;
       }
       if ((dx + dy + dt) % 2) {
           cout << "No\n";
           return;
       }
   }

   cout << "Yes\n";
}


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


    int t = 1;
//    cin >> t;
    while (t--) {
        one_case();
    }

    return 0;
}


Measured memory_bytes: 1408
#include<stdio.h>

int main()
{
    long long a,b,c,d,max;
    scanf("%lld %lld %lld %lld", &a,&b,&c,&d);
    max=a*c;
    if(max<a*d)
        max=a*d;

    if(max<b*c)
        max=b*c;

    if(max<b*d)
        max=b*d;

    printf("%lld",max);
    return 0;
}

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

using namespace std;

#define INF 1000000007
#define LINF (1LL << 60)
#define PI 3.14159265358979

typedef long long i64;
typedef pair<i64,i64> P;

inline i64 mod(i64 a, i64 m) { return (a % m + m) % m; }

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



int n, a[1010];
void solve(){
	cin >> n;
	for(int i = 0; i < n; i++){
		cin >> a[i];
	}
	
	int cnt = 0, ans = INF;
	for(int i = 1; i <= 100; i++){
		cnt = 0;
		for(int j = 0; j < n; j++){
			cnt += (i-a[j])*(i-a[j]);
		}
		chmin(ans,cnt);
	}
	cout << ans << endl;
}

int main(){
	std::cin.tie(0);
	std::ios::sync_with_stdio(false);
	int t = 1;
	//cin >> t;
	while(t--){
		solve();
	}
	
	return 0;
}


Measured memory_bytes: 256
A, B = map(int, input().split())

def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

a_fac = factorization(A)
b_fac = factorization(B)
ans = 0
is_one = False
for af in a_fac:
    for bf in b_fac:
        if af[0] == bf[0]:
            ans += 1
            if af[0] == 1:
                is_one = True
if is_one:
    print(ans)
else:
    print(ans+1)

Measured memory_bytes: 63456
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <iomanip>
#include <utility>
#include <tuple>
#include <functional>
#include <bitset>
#include <cassert>
#include <complex>
#include <stdio.h>
#include <time.h>
#include <numeric>
#include <unordered_map>
#include <unordered_set>
#define all(a) a.begin(),a.end()
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define pb push_back
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef long double ld;
typedef complex<ld> com;
constexpr int inf = 1000000000;
constexpr ll INF = 1000000000000000000;
constexpr ld EPS = 1e-12;
constexpr ld PI = 3.141592653589793238;
template<class T, class U> inline bool chmax(T &a, const U &b) { if (a < b) { a = b; return true; } return false; }
template<class T, class U> inline bool chmin(T &a, const U &b) { if (a > b) { a = b; return true; } return false; }


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

	int n, m;
	cin >> n >> m;
	vector<P> p(m);
	rep(i, m) {
		cin >> p[i].second >> p[i].first;
		p[i].first--;
	}
	sort(all(p));
	int ans = 0; int r = 0;
	rep(i, m) {
		if (r < p[i].second) {
			ans++;
			r = p[i].first;
		}
	}
	cout << ans << '\n';
}


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

int main(){
    int inputs[6];

    cin >> inputs[0] >> inputs[1];
    cin >> inputs[2] >> inputs[3];
    cin >> inputs[4] >> inputs[5];

    sort(inputs, inputs + 6);

    bool result = false;
    if(inputs[1]==inputs[2])
        result = true;
    if(!result){
        cout << "NO" << endl;
        return 0;
    }
    result = false;
    if (inputs[3] == inputs[4])
        result = true;
    if(!result){
        cout << "NO" << endl;
        return 0;
    }

    cout << "YES" << endl;

    return 0;
}

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

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

int main() {
	string ans = "NO";
	vector<int> N(4);
	rep(i,4) cin >> N.at(i);
	sort(N.begin(), N.end());
	if (N[0] == 1 and N[1] == 4 and N[2] == 7 and N[3] == 9){
		ans = "YES";
	}
	cout << ans << endl;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(x)(x).begin(), (x).end() // 昇順ソート
#define rall(v)(v).rbegin(), (v).rend() // 降順ソート
#define INF 1LL << 60
typedef long long int LL;
typedef long long int ll;
#define pll pair < ll, ll >
#define F first
#define S second
const int MOD = 1000000007;
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 (a > b) { a = b; return true; } return false; }
// 任意のlogは　対数の底の変換を使う    log(N) / log(任意の底)

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

    rep(i,3)cout << S[i];
    cout << endl;
}

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

#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(obj) (obj).begin(), (obj).end()
#define INF 1e9
#define LINF 1e15
typedef long long ll;


int main() {
    int N; cin >> N;
    vector<ll> a(3*N);
    REP(i,3*N) cin >> a[i];

    priority_queue<ll, vector<ll>, greater<ll>> L;
    priority_queue<ll> R;
    vector<ll> l_sum(N+1,0);
    vector<ll> r_sum(N+1,0);

    REP(i,N){
        L.push(a[i]);
        l_sum[0] += a[i];
    }
    REP(i,N){
        if(L.top() < a[N+i]){
            l_sum[i+1] = l_sum[i] + a[N+i] - L.top();
            L.pop();
            L.push(a[N+i]);
        }else{
            l_sum[i+1] = l_sum[i];
        }
    }

    REP(i,N){
        R.push(a[3*N-1-i]);
        r_sum[0] += a[3*N-1-i];
    }
    REP(i,N){
        if(R.top() > a[2*N-1-i]){
            r_sum[i+1] = r_sum[i] + a[2*N-1-i] - R.top();
            R.pop();
            R.push(a[2*N-1-i]);
        }else{
            r_sum[i+1] = r_sum[i];
        }
    }

    reverse(ALL(r_sum));

    ll ans = - LINF;
    REP(i,N+1){
        //cout << l_sum[i] << ", " << r_sum[i] << endl;
        ans = max(ans,l_sum[i] - r_sum[i]);
    }
    cout << ans << endl;
    

    return 0;
}

Measured memory_bytes: 9456
def gcd(n,m):
    if n < m:
        t = n
        n = m
        m = t
    r = n % m
    while r > 0:
        n, m = m, r
        r = n % m
    return m
N = int(input())
T = [int(input()) for _ in range(N)]
ans = T[0]
for i in range(1,N):
    g = gcd(ans,T[i])
    ans = ans*T[i]//g
print(ans)

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

using namespace std;
typedef long long ll;
//typedef unsigned long long ll;

#define rep(i, n) for (int i = 0; i < (n); ++i)
//#define rep(i, n) for (ll i = 0; i < (n); ++i)
//#define sz(x) ll(x.size())
//typedef pair<ll, int> P;
typedef pair<ll, ll> P;
//const double INF = 1e10;
const ll INF = LONG_LONG_MAX / 10;
//const ll INF = 1e15;
const ll MINF = LONG_LONG_MIN;
//const int INF = INT_MAX / 10;
#define cmin(x, y) x = min(x, y)
#define cmax(x, y) x = max(x, y)
//typedef pair<int, int> P;
//typedef pair<double, double> P;

bool contain(set<P> &s, P a) { return s.find(a) != s.end(); }

//ifstream myfile("C:\\Users\\riku\\Downloads\\0_00.txt");
//ofstream outfile("log.txt");
//outfile << setw(6) << setfill('0') << prefecture << setw(6) << setfill('0') << rank << endl;
// std::cout << std::bitset<8>(9);


void print_line(vector<ll> &line) {
    if (line.size() == 0ll) {
        cout << endl;
        return;
    }
    for (ll i = 0; i < line.size(); i++) {
        cout << line[i];
        if (i == line.size() - 1) cout << endl;
        else cout << ' ';
    }
}


typedef priority_queue<long long, vector<long long>, greater<long long>> PQ_ASK;
const int mod = 1000000007;

int main() {
    set<ll> a;
    int q;
    cin >> q;
    rep(i, q) {
        int command;
        ll x;
        cin >> command >> x;

        if (command == 0) {
            a.insert(x);
            cout << a.size() << endl;
        } else if (command == 1) {
            cout << (a.find(x) != a.end()) << endl;
        } else if (command == 2) {
            a.erase(x);
        } else if (command == 3) {
            ll l, r;
            l = x;
            cin >> r;
            for (auto it = a.lower_bound(l); it != a.end() && *it <= r; it++) {
                cout << *it << endl;
            }
        }

    }

}



Measured memory_bytes: 12428
#include "bits/stdc++.h"

using namespace std;

const long mod = 1e9 + 7;

void solve()
{
	int N;
	cin >> N;
	vector<int> as(N), nx[200020];
	for (int i = 0; i < N; i++)
	{
		cin >> as[i];
		nx[as[i]].push_back(i);
	}
	for (int i = 0; i < 200020; i++)
	{
		nx[i].push_back(N+1);
	}
	vector<long> dp(N+1);
	dp[0] = 1;
	for (int i = 0; i < N; i++)
	{
		int a = as[i];
		int j = *lower_bound(nx[a].begin(), nx[a].end(), i + 1);
		if (j != N+1 && j != i+1)
		{
			dp[j] += dp[i];
			dp[j] %= mod;
		}
		dp[i+1] += dp[i];
		dp[i+1] %= mod;
		//cout <<i << ' ' << j << ' ' << dp[i] << endl;
	}
	cout << dp[N] << endl;
}

int main(void)
{
	solve();
	//cout << "yui(*-v・)yui" << endl;
	return 0;
}


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

int main(void) {
	int a, b, c;
	cin >> a >> b >> c;
	int count = 0;
	for (int i = a; i <= b; ++i) {
		if (c % i == 0) count++;
	}
	cout << count << endl;

	return 0;
}


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

main(){

  vector<ll> a(3);
  rep(i,3)cin>>a[i];
  
  sort(a.begin(),a.end());
  ll cnt=0;
  while(a[1]+2<=a[2]){
    cnt++;
    a[1]+=2;
  }
  while(a[0]+2<=a[1]){
    cnt++;
    a[0]+=2;
  }

  using T4 = tuple<ll,ll,ll,ll>;
  priority_queue<T4,vector<T4>,greater<>> que;
  que.emplace(cnt,a[0],a[1],a[2]);
  while(!que.empty()){
    ll ans,x,y,z;
    tie(ans,x,y,z) = que.top();
    que.pop();
    if(x==y&&y==z){
      cout<<ans<<endl;
      return 0;
    }
    ans++;
    que.emplace(ans,x+1,y+1,z);
    que.emplace(ans,x+1,y,z+1);
    que.emplace(ans,x,y+1,z+1);
  }

}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define all(V) V.begin(),V.end()
const ll MOD = 1000000007;

int A[10010];

int main() {
	for (int i = 0;i < 10010;i++)A[i] = 0;
	int N;
	cin >> N;
	int K;
	for (int i = 1;i <= 199;i++) {
		for (int j = 1;j <= 199;j++) {
			for (int k = 1;k <= 199;k++) {
				K = i * i +
					j * j +
					k * k +
					i * j +
					j * k +
					k * i;
				if (K > 10000)continue;
				A[K]++;
			}
		}
	}
	for (int i = 1;i <= N;i++) {
		cout << A[i] << "\n";
	}
}

Measured memory_bytes: 3620
#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<iomanip>
#include<iso646.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>

using std::cin;
using std::cout;
using std::endl;

#define FOR(counter,initial_value,condition) for(int counter = initial_value; counter < condition;counter++)

int main()
{
	int x,t;
	cin >> x >> t;
	x -= t;
	cout << ((x < 0) ? 0 : x) << endl;
}

Measured memory_bytes: 256
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
long long a[200005];
long long n;
int main()
{
	cin >> n;
	for (long long int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	sort(a, a + n);
	int flag = 0;
	for (long long int i = 0; i < n; i++)
	{
		if (a[i] == a[i + 1])
		{
			flag = 1;
			break;
		}
	}
	if (flag == 0)
	{
		cout << "YES";
	}
	else
	{
		cout << "NO";
	}

	return 0;
}

Measured memory_bytes: 1792
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        long N = scanner.nextLong();
        long K = scanner.nextLong();

        long abs = Math.abs(N - K);
        if (abs > N) {
            System.out.println(N);
            return;
        }

        if (K > N) {
            System.out.println(Math.abs(N - K));
            return;
        }

        long div = N / K;
        long x = N - (K * div);
        abs = Math.abs(x - K);
        if (x > abs) {
            System.out.println(abs);
        } else {
            System.out.println(x);
        }
    }
}


Measured memory_bytes: 23124
#include<iostream>
#include<cmath>
using namespace std;
int main() {
    int x;
    cin >> x;
    if (x == 1) {
        cout << 1 << endl;
        return 0;
    }
    int b = 2, res = 0;
    int s = sqrt(x);
    while (b <= s) {
        for (int p = 2; ; ++p) {
            int bp = pow(b, p);
            if (bp == x) {
                cout << x << endl;
                return 0;
            } else if (bp > x) {
                break;
            } else if (res < bp) {
                res = bp;
            }
        }
        ++b;
    }
    cout << res << endl;
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(x)(x).begin(), (x).end() // 昇順ソート
#define rall(v)(v).rbegin(), (v).rend() // 降順ソート
#define INF 1 LL << 60
typedef long long int LL;
typedef long long int ll;
#define pll pair < ll, ll >
#define F first
#define S second
const int MOD = 1000000007;
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 (a > b) { a = b; return true; } return false; }
// 任意のlogは　対数の底の変換を使う    log(N) / log(任意の底)

int main() {
    int N;cin >> N;
    vector<LL> A(N);rep(i,N)cin >> A[i];

    LL ans = 0;

    rep(i,N){
        ans += (A[i]/2);
        A[i] %= 2;
        if(i != N-1 && A[i] == 1 && A[i+1] > 0){
            ans++;
            A[i+1]--;
        }
    }

    cout << ans << endl;
}

Measured memory_bytes: 1024
#include <bits/stdc++.h>
#define FOR(i,k,n) for(ll i=(k);i<(ll)(n);++i)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) begin(x),end(x)
 
using namespace std;
using namespace std::string_literals;
using ll = int64_t;
using vecint = vector<int>;
using vecll = vector<ll>;

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  int a,b;
  cin>>a>>b;
  cout<<a*b<<endl;
  return 0;
}


Measured memory_bytes: 3692
import copy

h, w, k = map(int, input().split())
c = [list(input()) for _ in range(h)]


def count(c):
    cnt = 0
    for i in range(len(c)):
        for j in range(len(c[i])):
            if "#" == c[i][j]:
                cnt += 1
    return cnt


def pattenrs(i, n, str, lst):
    if i == n:
        lst.append(str)
        return
    pattenrs(i + 1, n, str + "0", lst),
    pattenrs(i + 1, n, str + "1", lst)


patterns_i = []
pattenrs(0, h, "", patterns_i)

patterns_j = []
pattenrs(0, w, "", patterns_j)

total_black = count(c)
res = 0
for pattern_i in patterns_i:
    for pattern_j in patterns_j:
        copied = copy.deepcopy(c)
        cnt = total_black
        i_list = list(map(int, pattern_i))
        j_list = list(map(int, pattern_j))
        for i in range(len(i_list)):
            for j in range(len(j_list)):
                if 1 == i_list[i] or 1 == j_list[j]:
                    cnt -= 1 if "#" == copied[i][j] else 0
        res += 1 if cnt == k else 0

print(res)


Measured memory_bytes: 74460
#include <bits/stdc++.h>
using namespace std;
//make_tuple emplace_back next_permutation push_back make_pair second first setprecision

#if MYDEBUG
#include "lib/cp_debug.h"
#else
#define DBG(...) ;
#endif

using LL = long long;
constexpr LL LINF=334ll<<53;
constexpr int INF=15<<26;
constexpr LL  MOD=1E9+7;

struct Problem{
    string s;
    multiset<pair<int,int>> m;
    vector<int> mask;
    Problem(string s):s(s),mask(s.size()){};

    void solve(){
        int cnt =0;
        for(int i=0; i<(int)s.size(); ++i){
            cnt^=(1<<(s[i]-'a'));
            m.emplace(cnt,i);
            mask[i]=cnt;
        }
        queue<pair<int,int>> Q;
        Q.emplace(-1,0);
        while(1){
            auto now=Q.front();
            Q.pop();
            int nowmask=now.first<0?0:mask[now.first];
            auto lb = m.lower_bound({nowmask,now.first});
            while(lb!=m.end() and lb->first==nowmask){
                if(lb->second==(int)s.size()-1){
                    cout << now.second+1 <<endl;
                    return ;
                }
                if(lb->second>now.first){
                    Q.emplace(lb->second,now.second+1);
                    lb = m.erase(lb);
                }else {
                    ++lb;
                }
            }
            for(int i=0; i<26; ++i){
                int newmask = nowmask^(1<<i);
                auto lb = m.lower_bound({newmask,now.first});
                while(lb!=m.end() and lb->first==newmask){
                    if(lb->second==(int)s.size()-1){
                        cout << now.second+1 <<endl;
                        return ;
                    }
                    if(lb->second>now.first){
                        Q.emplace(lb->second,now.second+1);
                        lb = m.erase(lb);
                    }else {
                        ++lb;
                    }
                }
            }
        }

    }
};

int main(){
    cin.tie(0);
    ios_base::sync_with_stdio(false);
    string s;
    cin >> s;
    Problem p(s);
    p.solve();
    return 0;
}



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

int main() {
    double ans=0.0;
    int N; cin >> N;
    vector<double> A(N);

    for (int i = 0; i < N; ++i) {
        cin >> A[i];
        A[i] = 1/A[i];
        ans += A[i];
    }

    cout << setprecision(14) << 1/ans << endl;

    return 0;
}

Measured memory_bytes: 256
a = list(map(int,input().split()))
a.sort()

if (a[1]-a[0])%2 == 0:
    b = a[2]-a[1] + int((a[1]-a[0])/2)
else:
    b = a[2]-a[1] + int((a[1]-a[0])/2)+2

print(b)


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

int W, H, N;
int X1[1005], X2[1005], Y1[1005], Y2[1005];
bool fld[3005][3005];

int compress(int*x1, int*x2, int w) {
	vector<int>xs;
	rep(i, N)for (int d = -1; d <= 1; d++) {
		int tx1 = x1[i] + d, tx2 = x2[i] + d;
		if (0 <= tx1&&tx1 < w)xs.push_back(tx1);
		if (0 <= tx2&&tx2 < w)xs.push_back(tx2);
	}
	sort(xs.begin(), xs.end());
	xs.erase(unique(xs.begin(), xs.end()), xs.end());
	rep(i, N) {
		x1[i] = find(xs.begin(), xs.end(), x1[i]) - xs.begin();
		x2[i] = find(xs.begin(), xs.end(), x2[i]) - xs.begin();
	}
	return xs.size();
}
int dx[]{ 1,-1,0,0 }, dy[]{ 0,0,1,-1 };
int main() {
	while (scanf("%d%d", &W, &H), W) {
		scanf("%d", &N);
		rep(i, N) {
			scanf("%d%d%d%d", &X1[i], &Y1[i], &X2[i], &Y2[i]);
			X2[i]--; Y2[i]--;
		}
		W = compress(X1, X2, W);
		H = compress(Y1, Y2, H);
		memset(fld, 0, sizeof(fld));
		rep(i, N) {
			for (int y = Y1[i]; y <= Y2[i]; y++)
				for (int x = X1[i]; x <= X2[i]; x++)
					fld[y][x] = true;
		}
		int ans = 0;
		for (int y = 0; y < H; y++) {
			for (int x = 0; x < W; x++) {
				if (fld[y][x])continue;
				ans++;
				queue<P>que;
				que.push(P(x, y));
				while (!que.empty()) {
					int sx = que.front().first, sy = que.front().second;
					que.pop();
					rep(i, 4) {
						int tx = sx + dx[i], ty = sy + dy[i];
						if (tx < 0 || W <= tx || ty < 0 || H <= ty || fld[ty][tx])continue;
						que.push(P(tx, ty));
						fld[ty][tx] = true;
					}
				}
			}
		}
		printf("%d\n", ans);
	}
}

Measured memory_bytes: 12076
from collections import defaultdict

n, m = map(int, input().split())
PS = [input().split() for _ in range(m)]
ac = defaultdict(bool)
wa = defaultdict(int)
cost = 0
score = 0
for p, s in PS:
  if s == 'AC' and not ac[p]:
    score += 1
    cost += wa[p]
    ac[p] = True
  if s == 'WA' and not ac[p]:
    wa[p] += 1
print(score, cost)

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

int main() {
    int n;
    string s;
    cin >> n >> s;
    vector<char> alpha;
    for (char c = 'A'; c <= 'Z'; c++) {
        alpha.push_back(c);
    }
    int mod = 'A' + 0;
    for (char x : s) {
        int i = (x + n - mod) % 26;
        cout << alpha[i];
    }
    cout << endl;
}


Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <functional>
#include <iostream>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <stack>
#include <string>
#include <vector>
 
using namespace std;
typedef long long ll;
using gra = vector<vector<ll>>;
using gram = vector<unordered_map<ll,ll>>;
 
typedef unsigned long long ull;
 
template <class T> inline bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; }
template <class T> inline bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; }
 
template <class T> T gcd(T a, T b) { return b ? gcd(b, a % b) : a; }
template <class T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template <class T> T dup(T a, T b) { return (a + b - 1) / b; }
template <class T> T modpow(T x, T p, T m) { T a=1; while(p){ if(p%2)a =a*x%m; x = x+x%m; p/=2; } return a; }
// template <class T> void prim(T a) { for(ll i=0;i<a.size();++i) { cout << a[i]; } cout << "\n"; }
 
#define mod 1000000007LL
#define INF 10000000000000000LL
 
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define rep1(i, n) for (int i = 1; i <= n; ++i)
#define rrep(i, n) for (int i = (n - 1); i >= 0; --i)
#define rrep1(i, n) for (int i = n; i > 0; --i)
 
#define pri(x) cout << (x) << "\n"
#define pri2(x, y) cout << (x) << " " << (y) << "\n"
#define pri3(x, y, z) cout << (x) << " " << (y) << " " << (z) << "\n"
//#define modpow(x, p, m) { ll a=1; while(p){ if(p%2)a =a*x%m; x = x+x%m; p/=2; } return a; }
 
#define m0(h) memset(h, 0, sizeof(h))
#define m1(h) memset(h, 1, sizeof(h))
#define m(h, n) memset(h, (n), sizeof(h))
#define all(n) (n).begin(),(n).end()
#define bit(n) (1LL << (n))
#define pb push_back
 
//#ifdef LOCAL
//
//#define dpri(...) fprintf(stderr, __VA_ARGS__)
//#define pria(g) rep(i,g.size()){ cout << i << "{"; rep(j,g[i].size()) cout << g[i][j] << " "; cout << "}" << "\n"; }
//#else
//#define dpri(...) 42
//#define pria(g) 42
//#endif
 
 
 
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  // ---------------------
  // コーディング開始
  // ---------------------
  int n;
  cin >> n;
  ll pin=0;
  for(ll i=100;i<=1000000;i+=100){
    pin+=5;
    if(n>=i && n<=i+pin){
      pri(1);
      return 0;
    }
  }
  pri(0);
  return 0;
}







Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <cmath>
#include<algorithm>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<iomanip>
#define _USE_MATH_DEFINES
#include <math.h>
#include <functional>
#include<complex>
using namespace std;

#define rep(i,x) for(ll i=0;i<x;i++)
#define repn(i,x) for(ll i=1;i<=x;i++)

typedef long long ll;
const ll INF = 1e17;
const ll MOD = 1000000007;
const ll MAX = 4000001;
const double eps = 1E-18;

ll max(ll a, ll b) {
	if (a > b) { return a; }
	return b;
}

ll min(ll a, ll b) {
	if (a > b) { return b; }
	return a;
}

ll gcd(ll a, ll b) {
	if (b == 0) { return a; }
	if (a < b) { return gcd(b, a); }
	return gcd(b, a % b);
}

ll lcm(ll a, ll b) {
	return a / gcd(a, b) * b;
}

struct edge {
	ll ind;
	ll fr;
	ll to;
	ll d;
};

class mint {
	long long x;
public:
	mint(long long x = 0) : x((x% MOD + MOD) % MOD) {}
	mint operator-() const {
		return mint(-x);
	}
	mint& operator+=(const mint& a) {
		if ((x += a.x) >= MOD) x -= MOD;
		return *this;
	}
	mint& operator-=(const mint& a) {
		if ((x += MOD - a.x) >= MOD) x -= MOD;
		return *this;
	}
	mint& operator*=(const  mint& a) {
		(x *= a.x) %= MOD;
		return *this;
	}
	mint operator+(const mint& a) const {
		mint res(*this);
		return res += a;
	}
	mint operator-(const mint& a) const {
		mint res(*this);
		return res -= a;
	}
	mint operator*(const mint& a) const {
		mint res(*this);
		return res *= a;
	}

	mint pow(ll t) const {
		if (!t) return 1;
		mint a = pow(t >> 1);
		a *= a;
		if (t & 1) a *= *this;
		return a;
	}

	// for prime MOD
	mint inv() const {
		return pow(MOD - 2);
	}
	mint& operator/=(const mint& a) {
		return (*this) *= a.inv();
	}
	mint operator/(const mint& a) const {
		mint res(*this);
		return res /= a;
	}

	friend ostream& operator<<(ostream& os, const mint& m) {
		os << m.x;
		return os;
	}
};

mint pw(mint a, ll b) {
	if (b == 0) { return 1; }
	mint ret = pw(a, b>>1);
	ret *= ret;
	if (b & 1) { ret *= a; }
	return ret;
}

typedef vector<ll> vll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<vector<ll>>> vvvll;

typedef vector<mint> vmint;
typedef vector<vector<mint>> vvmint;
typedef vector<vector<vector<mint>>> vvvmint;


//////////////////////////
ll K, N;

void prev(vector<ll>& A) {
	ll M = A.size();
	if (A[M - 1] == 1) { A.pop_back(); return; }

	A[M - 1]--;

	rep(i, N - M) {
		A.push_back(K);
	}


}

int main() {
	cin >> K >> N;

	if (K % 2 == 0) {
		cout << K/2 << " ";

		repn(i, N - 1) {
			cout << K << " ";
		}
	}

	else {
		vector<ll> A;
		rep(i, N)A.push_back((K + 1) / 2);

		rep(i, N / 2) {
			//rep(i, A.size()) { cout << A[i] << " "; }
			//cout << endl;
			prev(A);
		}

		rep(i, A.size()) { cout << A[i] << " "; }
	}
	
}


Measured memory_bytes: 6512
n = int(input())
arr = [int(x) for x in input().split()]

def countTwoInFactor(n):
   def countTwoInFactori(n, acc):
      return countTwoInFactori(n / 2, acc + 1) if n % 2 == 0 else acc
   return countTwoInFactori(n, 0)

arr2 = [countTwoInFactor(x) for x in arr]
arr2.sort()
print(arr2[0])


Measured memory_bytes: 3060
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;

int main() {
    int N;long long cnt=0; scanf("%d",&N);
    vector <long long> A(N), B(N);
    for(int i=0;i<N;i++) scanf("%d%d",&A[i],&B[i]);
    for(int i=N-1;i>=0;i--){
        int a=A[i]%B[i];
        if(a) cnt+=B[i]-a;
        if(i) A[i-1]+=cnt;
    }
    cout << cnt << endl;
    return 0;
}

Measured memory_bytes: 1792