akhauriyash/Code-Regression huggingface dataset:
from collections import Counter
N = int(input())
A = list(map(int,input().split()))
"""
普通にやると、O(N^2)かかる
エラトステネスの篩でできないか？
まず、長さ10^6+1のflag配列を用意する。初期値は全部1。
Aに含まれる値以外は0にする。
で、エラトステネスの篩と同じことをする。
"""
A = Counter(A)
flags = [1]*(1000001)
for i in range(1000001):
    if i not in A:
        flags[i] = 0
ans = 0
for i in range(1000001):
    if flags[i] == 1:
        ans += 1
        for j in range(i*2,1000001,i):
            flags[j] = 0

for i in range(1000001):
    if flags[i] == 1:
        if A[i] > 1:
            ans -= 1

print(ans)


Measured memory_bytes: 124660
#include<cstdio>
#define K 1000001
#define M 50005
#define N 300003
inline int abv(int x){return x<0?-x:x;}
int gcd(int x,int y){return y?gcd(y,x%y):x;}
int a[M],b[M],c[M],f[N],h,i,j,k,m,n,o,p,q,s[N];bool g[2][K];
int find(int u){return f[u]==u?u:f[u]=find(f[u]);}
inline void merge(int u,int v){if((u=find(u))!=(v=find(v)))s[u]<s[v]?u^=v^=u^=v:0,s[f[v]=u]+=s[v];}
inline bool check(int u,int v,int w)
{
    for(j=0;j<2;j++)for(k=0;k<3;k++)if(g[j][(w+(3-k)*o)%p]&&find((u-1)*6)==find((v-1)*6+3*j+k))return true;
    return false;
}
int main()
{
    scanf("%d%d%d%d",&n,&m,&q,&p);
    for(i=1;i<=m;i++)scanf("%d%d%d",a+i,b+i,c+i),o=gcd(abv(c[i]-c[1]),o);
    for(i=1,o=!o?p:o,p=gcd(p,3*o),h=c[1]%o;i<=m;i++)c[i]=c[i]/o%3;
    for(i=0;i<6*n;i++)s[f[i]=i]=1;
    for(i=0,j=h%p;!g[i][j];j=(j<<1)%p,i^=1)g[i][j]=true;
    for(i=1;i<=m;i++)merge((a[i]-1)*6,(b[i]-1)*6+3+c[i]),merge((a[i]-1)*6+1,(b[i]-1)*6+3+(2+c[i])%3),merge((a[i]-1)*6+2,(b[i]-1)*6+3+(1+c[i])%3),merge((a[i]-1)*6+3,(b[i]-1)*6+c[i]),merge((a[i]-1)*6+4,(b[i]-1)*6+(2+c[i])%3),merge((a[i]-1)*6+5,(b[i]-1)*6+(1+c[i])%3);
    for(int u,v,w;q--;)scanf("%d%d%d",&u,&v,&w),puts(check(v,u,(w+h)%p)?"YES":"NO");
    return 0;
}

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


public class Main {
	static int L;
	static int count;
	static int a[]=new int[21];
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int n;

		while(true){
			n=sc.nextInt();
			L=sc.nextInt();
			count=0;
			if(n+L==0) break;
			a[count++]=n;
			f(n);
		}
	}

	static void f(int n){
		String str=Integer.toString(n);
		int k=str.length();
		for(int i=0;i<L-k;i++){
			str="0"+str;
		}
		//System.out.println(str);
		char ch[]=str.toCharArray();
		Arrays.sort(ch);
		char ch2[]=str.toCharArray();
		int j=0;
		for(int i=ch.length-1;0<=i;i--){
			ch2[j++]=ch[i];
		}
		int min=Integer.parseInt(String.valueOf(ch));
		int max=Integer.parseInt(String.valueOf(ch2));

		//System.out.println(min+" "+max);
		a[count++]=max-min;
		if(check()) return;
		f(a[count-1]);
	}
	static boolean check(){
		for(int j=0;j<count;j++){
			for(int i=j+1;i<count;i++){
				if(a[j]==a[i]){
					System.out.println(j+" "+a[i]+" "+(i-j));
					return true;
				}
			}
		}
		return false;
	}
}

Measured memory_bytes: 12000
#include <iostream>
#include <vector>
#include <string>
#include <cmath>

#define REP(i,n) for(int i = 0; i < (n); i++)
#define REPC(x,c) for(auto x:(c))
#define FOR(i, b, e) for(int i = (b); i < (e); i++)
#define VS vector<string>
#define VI vector<int>
#define VVI vector<vector<int>>

using namespace std;

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

	if (x <= 3) { cout << 1 << endl; return 0; }
	int max = 0;
	FOR(i,2,33){
		FOR(j, 2, 10) {
			int tmp = pow(i, j);
			if (tmp <= x) {
				if (tmp > max) { max = tmp; }
			}
			if (tmp > x) {
				break;
			}
		}
	}
	cout << max << endl;
}

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

int gcd(int a, int b){
    if(a < b) swap(a, b);
    int r = a % b;
    return (r == 0 ? b : gcd(b, r));
}

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

    int a, b;
    while(cin >> a >> b){
        cout << gcd(a, b) << endl;
    }

    return 0;
}


Measured memory_bytes: 3088
N=int(input())
h=list(map(int,input().split()))

dp=[0 for i in range(N)]

dp[1]=abs(h[1]-h[0])
for j in range(2,N):
  dp[j]=min(dp[j-1]+abs(h[j]-h[j-1]),dp[j-2]+abs(h[j]-h[j-2]))
            
print(dp[N-1])

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

int main() {
    int a, b;
    char op;
    cin >> a >> op >> b;
    if(op=='+') cout << a+b << endl;
    else cout << a-b << endl;
    return 0;
}

Measured memory_bytes: 256
#include<stdio.h>
#include<stdlib.h>


int comparator(const void *a, const void *b);
long long gcd(long long a, long long b);

long long A[1000001];
int main(void) {
  long long N;
  long long lesser = 1000000001;

  scanf("%lld", &N);
  for(long long i=0;i<N;i++) {
    scanf("%lld", &A[i]);
    lesser = lesser < A[i] ? lesser:A[i];
  }

  for(long long i=0;i<N;i++) {
    lesser = gcd(lesser, A[i]);
  }
  printf("%lld\n", lesser);

  return 0;
}

long long gcd(long long a, long long b){
  return b!=0 ? gcd(b, a%b): a;
}


Measured memory_bytes: 896
package main

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

var sc = bufio.NewScanner(os.Stdin)

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

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

type runes []rune

func (rs runes) Len() int           { return len(rs) }
func (rs runes) Swap(i, j int)      { rs[i], rs[j] = rs[j], rs[i] }
func (rs runes) Less(i, j int) bool { return rs[i] < rs[j] }
func sortString(s string) string {
	r := []rune(s)
	sort.Sort(runes(r))
	return string(r)
}

func main() {
	sc.Split(bufio.ScanWords)
	var N int
	// fmt.Scanf("%d", &N)
	N = nextInt()
	mp := make(map[string]int)
	A := make([]string, N)
	for i := 0; i < N; i++ {
		A[i] = next()
		mp[sortString(A[i])]++
	}

	ans := 0
	for _, n := range mp {
		ans += n * (n - 1) / 2
	}
	fmt.Println(ans)

}


Measured memory_bytes: 15360
import java.util.*;

public class Main {

	public static void main (String[] args)  {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] arrA = new int[n + 1];
		int[] arrB = new int[n + 1];
		int[] arrC = new int[n];
		for (int i = 1; i <= n; i++) {
			arrA[i] = sc.nextInt();
		}
		for (int i = 1; i <= n; i++) {
			arrB[i] = sc.nextInt();
		}
		for (int i = 1; i < n; i++) {
			arrC[i] = sc.nextInt();
		}
		int prev = -1;
		int total = 0;
		for (int i = 1; i <= n; i++) {
			int x = arrA[i];
			total += arrB[x];
			if (prev + 1 == x) {
				total += arrC[prev];
			}
			prev = x;
		}
		System.out.println(total);
	}
}


Measured memory_bytes: 21716
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <utility>
#include <cstdio>
#include <iomanip>
#include <cmath>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <stdlib.h>
#include <set>
typedef long long ll;
using namespace std;

int main() {
	int a,b;
	cin>>a>>b;
	if(a+b>=10){
		cout<<"error"<<endl;
	}else{
		cout<<a+b<<endl;
	}
	return 0;
}


Measured memory_bytes: 256
from itertools import accumulate

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

Bs = list(accumulate(As))
amari = sorted([B%M for B in Bs])
amari += [10**10]
# print(amari)

cnt = 1
ans = 0
tmp = amari[0]
for a in amari[1:]:
    # print(a,cnt)
    if tmp != a:
        # print(a,cnt)
        ans += cnt*(cnt-1)//2 #二項係数を足す
        if tmp == 0:
            # 0 のときだけcnt分足す
            ans += cnt
        # 初期化
        tmp = a
        cnt = 1
    else:
        cnt += 1

print(ans)    


Measured memory_bytes: 17216
#include<ctime>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<cassert>
#include<string>
#include<sstream>
#include<fstream>
#include<deque>
#include<queue>
#include<vector>
#include<map>
#include<list>
#include<stack>
#include<set>
#include<bitset>
#include<iomanip>
#include<utility>
#include<functional>
#include<cctype>
#include<cerrno>
#include<cfloat>
#include<ciso646>
#include<climits>
#include<clocale>
#include<complex>
#include<csetjmp>
#include<csignal>
#include<cstdarg>
#include<cstddef>
#include<cwchar>
#include<cwctype>
#include<exception>
#include<locale>
#include<numeric>
#include<new>
#include<stdexcept>
#include<limits>
using namespace std;

#define ll long long
#define INF 1e9
#define rep(i,n) for(int (i)=0;(i)<n;i++)
#define REP(i,n) for(int (i)=1;(i)<=n;i++)
#define mk(a,b) make_pair(a,b)
#define fi first
#define se second
#define pii pair<int,int>

int readint()
{
	char c;
	while(c=getchar(),(c<'0'||c>'9')&&c!='-');
	bool flag=(c=='-');
	if(flag)c=getchar();
	int x=0;
	while(c>='0'&&c<='9')
	{
		x=x*10+c-48;
		c=getchar();
	}
	return flag?-x:x;
}

const int maxn=100005;
int n,m;
ll ans=(ll)INF*(ll)INF;
int ar[maxn];
ll coef[maxn],cons[maxn];

void add(int l,int r,ll s[],int val){
	s[l]+=(ll)val;
	s[r+1]-=(ll)val;
}

void add_ans(int a,int b){
	if(a<b){
		add(1,a,coef,b-a);
		add(a+1,b,cons,-1);
		add(a+1,b,coef,1+b);
		add(b+1,m,coef,b-a);
	}
	else{
		add(a+1,m,coef,1+m+b);
		add(a+1,m,cons,-1);
		add(1,b,coef,1+b);
		add(1,b,cons,-1);
		add(b+1,a,coef,m-a+b);
	}
}

int main(){
	scanf("%d%d",&n,&m);
	rep(i,n)scanf("%d",&ar[i]);
	rep(i,n-1)add_ans(ar[i],ar[i+1]);
	REP(i,m){
		coef[i]+=coef[i-1];
		cons[i]+=cons[i-1];
//		cout<<i<<" "<<coef[i]<<" "<<cons[i]<<endl; 
	}
	REP(i,m){
		ll cur=coef[i]+cons[i]*i;
		ans=min(cur,ans);
	}
	printf("%lld",ans);
	return 0;
}

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

int main() {
    int N,M;
    cin >> N;
    cin >> M;
    vector<int> A(M);

    for (int i=0;i<M;i++) {
        cin >> A.at(i);
    }

    int ans = N;
    for (int i=0;i<M;i++) {
        ans -= A.at(i);
    }
    if ( ans >= 0) {
        cout << ans << endl;
    }
    else {
        cout << "-1" << endl;
    }

    return 0;
}

Measured memory_bytes: 3632
// sync

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>

const int N = 1e5 + 51;

int p[N];
int f(int x) { return x[p] ? x[p] = f(x[p]) : x; }

int n, m, q, op[N], x[N], y[N], cnt, c0;
int main() {
	scanf("%d%d%d", &n, &m, &q), cnt = n;
	for (int i = 1; i <= q; i++) {
		scanf("%d%d%d", x + i, y + i, op + i), x[i]++, y[i]++;
		int u = x[i], v = y[i];
		if (!op[i]) {
			c0++;
			if ((u = f(u)) != (v = f(v))) u[p] = v, cnt--;
		}
	}
	for (int i = 1; i <= q; i++)
		if (op[i] && f(x[i]) == f(y[i])) return puts("No"), 0;
	if (n - (c0 == q) <= m && m <= n - cnt + 1ll * cnt * (cnt - 1) / 2)
		puts("Yes");
	else
		puts("No");
}

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

int main() {
  int n; cin >> n;
  int S[13], H[13], C[13], D[13];
  for (int i = 0; i < 13; i ++) {
    S[i] = H[i] = C[i] = D[i] = 0;
  }

  for (int i = 0; i < n; i ++) {
    char t;
    int m;
    cin >> t >> m;
    if (t == 'H') H[m-1] = 1;
    else if (t == 'S') S[m-1] = 1;
    else if (t == 'C') C[m-1] = 1;
    else D[m-1] = 1;
  }

  for (int i = 0; i < 13; i ++) {
    if (!S[i]) cout << "S" << " " << i+1 << endl;
  }
  for (int i = 0; i < 13; i ++) {
    if (!H[i]) cout << "H" << " " << i+1 << endl;
  }
  for (int i = 0; i < 13; i ++) {
    if (!C[i]) cout << "C" << " " << i+1 << endl;
  }
  for (int i = 0; i < 13; i ++) {
    if (!D[i]) cout << "D" << " " << i+1 << endl;
  }
}



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

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int a, b; cin >> a >> b;
    float ans = 0;
    while(ans < 1010) {
        if(floor(ans*0.08) == a && floor(ans*0.1) == b)
            break;
        ans++;
    }
    if(ans > 1009) cout << -1;
    else cout << ans;
    return 0;
}

Measured memory_bytes: 256
#B
n = int(input())

a = list(map(int, input().strip().split()))
b = list(map(int, input().strip().split()))
c = list(map(int, input().strip().split()))

ans = 0
for i in range(n):
    ans += b[a[i]-1]
    if i >= 1 and (a[i-1] + 1 == a[i]):
        ans += c[a[i-1]-1]

print(ans)


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

int main() {
  int N;
  cin >> N;
  
  int min = 10000;
  for (int i = 0; i < N; i++) {
    int x;
    cin >> x;
    
    int y = 0;
    while (true) {
      if ((x % 2) == 0) {
        x /= 2;
        y++;
      }else{
        break;
      }
    }
    
    if (y < min) {
      min = y;
    }
  }
  
  cout << min << endl;
}

Measured memory_bytes: 256
from collections import Counter

N = int(input())
S = list(input())

count = Counter(S)
R_list = [count[0]] * N
G_list = [count[0]] * N
B_list = [count[0]] * N
R_count = 0
G_count = 0
B_count = 0
for i in range(1, len(S)+1):
    if S[-i] == 'R':
        R_count += 1
    elif S[-i] == 'G':
        G_count += 1
    else:
        B_count += 1
    R_list[-i] = R_count
    G_list[-i] = G_count
    B_list[-i] = B_count

amount = 0
for i, s in enumerate(S):
    for k in range(i+1, len(S)):
        if S[i] == S[k]:
            continue
        else:
            check_set = set([S[i], S[k]])
            if 'R' not in check_set:
                amount += R_list[k]
            elif 'G' not in check_set:
                amount += G_list[k]
            else:
                amount += B_list[k]
            try:
                if S[2*k-i] not in check_set:
                    amount -= 1
            except:
                pass
print(amount)

Measured memory_bytes: 75440
#include "bits/stdc++.h"
#include<assert.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define int long long
const int inf = 1e17;
const int mod = 1000000007;
typedef pair<int, int> P;
typedef pair<int, P> PP;
vector<int>G[405];
int in[405];
int a[100005], b[100005], c[100005], d[100005];
int vst[405];
void dfs(int now) {
	for(int e:G[now]) {
		if (vst[e])continue;
		vst[e] = 1;
		dfs(e);
	}
}
signed main() {
	int n, h; cin >> n >> h;
	rep(i, n) {
		cin >> a[i] >> b[i] >> c[i] >> d[i];
		int x, y;
		if (c[i] == 0)x = a[i];
		else x = c[i] + h;
		if (d[i] == 0)y = b[i] + h;
		else y = d[i];
		G[x].push_back(y);
		in[y]++;
	}
	int cnt = 0;
	rep(i, h + 1) {
		int z = G[i].size();
		if (z-in[i]>=1) {
			cnt+=z-in[i];
			G[0].push_back(i);
			in[i]++;
		}
		else if (z != in[i]) {
			puts("NO"); return 0;
		}
	}
	for (int i = h + 1; i <= 2 * h; i++) {
		int z = G[i].size();
		if (in[i]-z>=1) {
			cnt-=in[i]-z;
			G[i].push_back(0);
			in[0]++;
		}
		else if (z != in[i]) {
			puts("NO"); return 0;
		}
	}


	if (cnt!=0) {
		puts("NO");
	}
	else {
		vst[0] = 1;
		dfs(0);
		rep(i, 2 * h + 1) {
			if (vst[i] == 0 && (in[i]||G[i].size())) {
				puts("NO"); return 0;
			}
		}

		puts("YES");
	}
}

Measured memory_bytes: 4864
#include <bits/stdc++.h>
#include <ext/hash_map>
#include <ext/numeric>

using namespace std;
using namespace __gnu_cxx;

#define REP(i,n) for( (i)=0 ; (i)<(n) ; (i)++ )
#define rep(i,x,n) for( (i)=(x) ; (i)<(n) ; (i)++ )
#define REV(i,n) for( (i)=(n) ; (i)>=0 ; (i)-- )
#define FORIT(it,x) for( (it)=(x).begin() ; (it)!=(x).end() ; (it)++ )
#define foreach(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();++it)
#define rforeach(it,c) for(__typeof((c).rbegin()) it=(c).rbegin();it!=(c).rend();++it)
#define foreach2d(i, j, v) foreach(i,v) foreach(j,*i)
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define SZ(x) ((int)(x).size())
#define MMS(x,n) memset(x,n,sizeof(x))
#define mms(x,n,s) memset(x,n,sizeof(x)*s)
#define pb push_back
#define mp make_pair
#define NX next_permutation
#define UN(x) sort(all(x)),x.erase(unique(all(x)),x.end())
#define CV(x,n) count(all(x),(n))
#define FIND(x,n) find(all(x),(n))-(x).begin()
#define ACC(x) accumulate(all(x),0)
#define PPC(x) __builtin_popcountll(x)
#define LZ(x) __builtin_clz(x)
#define TZ(x) __builtin_ctz(x)
#define mxe(x) *max_element(all(x))
#define mne(x) *min_element(all(x))
#define low(x,i) lower_bound(all(x),i)
#define upp(x,i) upper_bound(all(x),i)
#define NXPOW2(x) (1ll << ((int)log2(x)+1))
#define PR(x) cout << #x << " = " << (x) << endl ;

typedef unsigned long long ull;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int> > vvi;
typedef pair<int, int> pii;

const int OO = (int) 2e9;
const double eps = 1e-9;

const int N = 100005;

int n;
int h[N];
int dp[N];

int main() {
	std::ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
#ifndef ONLINE_JUDGE
//	freopen("in.txt", "rt", stdin);
//	freopen("out.txt", "wt", stdout);
#endif
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> h[i];
	MMS(dp, '?');
	dp[0] = 0;
	for (int i = 1; i < n; i++) {
		dp[i] = min(dp[i], dp[i - 1] + abs(h[i] - h[i - 1]));
		if (i - 2 >= 0)
			dp[i] = min(dp[i], dp[i - 2] + abs(h[i] - h[i - 2]));
	}
	cout << dp[n - 1] << endl;
	return 0;
}


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

typedef long long ll;
const int N = 1e4 + 5;

int n;
int a[N];
ll b[N];
bool pr[N];

bool check(int p)
{
    for (int k = 0; k < N; ++k)
        b[k] = 0;

    for (int i = 0; i <= n; ++i)
        b[i % (p - 1)] += (a[i] % p + p) % p;

    for (int i = 0; i < N; ++i)
        if (b[i] % p) return false;

    return true;
}

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

int main()
{
    scanf("%d", &n);

    int g = 0;
    for (int i = n; i >= 0; --i)
    {
        scanf("%d", a + i);
        g = gcd(g, abs(a[i]));
    }


    set<int> out;

    for (int x = 2; x * x <= g; ++x)
    {
        if (g % x) continue;
        while(g % x == 0) g /= x;
        out.insert(x);
    }
    if (g > 1) out.insert(g);

    for (int x = 2; x < N; ++x)
        pr[x] = true;
    for (int x = 2; x < N; ++x)
    {
        if (!pr[x]) continue;
        if (a[0] % x == 0 && check(x))
            out.insert(x);
        for (int y = x + x; y < N; y += x)
            pr[y] = false;
    }

    for (int p : out)
        printf("%d\n", p);
}


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

int main() {
  int N;
  cin >> N;
  
  int a = N / 1000;
  int b = (N % 1000) / 100;
  int c = (N % 100) / 10;
  int d = N % 10;

  if (b == c && (a == b || c == d)) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }
}

Measured memory_bytes: 256
#include <iostream>
#include <cstring>

const int INFTY = 2000000000;

void printArray(int * A, int n) {
    for (int i = 0; i < n - 1; i++) {
        std::cout << A[i] << " ";
    }
    std::cout << A[n - 1] << std::endl;
}

int merge(int * A, int left, int mid, int right) {
    int n1 = mid - left, n2 = right - mid;
    int L[n1 + 1], R[n2 + 1];
    std::memcpy(L, A + left, sizeof(int) * n1);
    std::memcpy(R, A + left + n1, sizeof(int) * n2);
    L[n1] = INFTY, R[n2] = INFTY;

    int i = 0, j = 0, count = 0;
    for (int k = left; k < right; k++) {
        if (L[i] <= R[j]) {
            A[k] = L[i];
            i++;
        } else {
            A[k] = R[j];
            j++;
        }
        count++;
    }
    return count;
}


long long mergeSort(int * A, int left, int right) {
    long long count = 0;
    if (left + 1 < right) {
        int mid = (left + right) / 2;
        count += mergeSort(A, left, mid);
        count += mergeSort(A, mid, right);
        count += merge(A, left, mid, right);
    }
    return count;
}


int main() {
    int n;
    std::cin >> n;
    int A[n];

    for (int i = 0; i < n; i++) {
        std::cin >> A[i];
    }
    
    long long count = mergeSort(A, 0, n);

    printArray(A, n);
    std::cout << count << std::endl;
}



Measured memory_bytes: 7036
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
  let stdin = stdin();
  let stdin = stdin.lock();
  let token: String = stdin
    .bytes()
    .map(|c| c.expect("failed to read char") as char)
    .skip_while(|c| c.is_whitespace())
    .take_while(|c| !c.is_whitespace())
    .collect();
  token.parse().ok().expect("failed to parse token")
}

fn read_n<T: FromStr>(n: usize) -> Vec<T> {
  read_n_logic::<T>(n, vec![])
}

fn read_n_logic<T: FromStr>(n: usize, mut a: Vec<T>) -> Vec<T> {
  match n {
    0 => a,
    _ => {
      a.push(read::<T>());
      read_n_logic(n - 1, a)
    }
  }
}

fn main() {
  let n = read::<usize>();
  let t = read::<f64>();
  let a = read::<f64>();
  let mut h = read_n::<f64>(n);

  for i in 0..h.len() {
    h[i] = t - h[i] * 0.006;
  }

  let mut near = (a - h[0]).abs();
  let mut answer = 0;

  for i in 1..h.len() {
    let distance = (a - h[i]).abs();
    if distance < near {
      near = distance;
      answer = i;
    }
  }

  println!("{}", answer + 1);
}


Measured memory_bytes: 4352
from collections import deque
def main():
  h,w = map(int,input().split())
  s = [input() for _ in range(h)]
  #print(sum([i.count(".") for i in s]))
  
  def bfs(st):
    que = deque([st])
    c = [[0]*w for _ in range(h)]
    while que:
      ph,pw = que.popleft()
      step = c[ph][pw] + 1
      for dh,dw in ((1,0),(0,1),(-1,0),(0,-1)):
        nh = ph+dh
        nw = pw+dw
        if nh<0 or nw<0 or nh>=h or nw>=w:
          continue
        if s[nh][nw]=="#" or c[nh][nw] != 0:
          continue
        c[nh][nw] = step
        if (nh,nw) == (h-1,w-1):
          return step
        que.append((nh,nw))
  
  result = bfs((0,0))
  if result:
    return sum([i.count(".") for i in s])-result-1
  else:
    return -1

print(main())

Measured memory_bytes: 3316
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
 
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 _overload3(_1,_2,_3,name,...) name
#define _rep(i,n) repi(i,0,n)
#define repi(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload3(__VA_ARGS__,repi,_rep,)(__VA_ARGS__)

int main(){
    int n;
    cin>>n;
    vector<vector<int>> g(n);
    rep(i,n-1){
        int a,b;
        cin>>a>>b;
        --a;--b;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    priority_queue<int> cs;
    vector<int>csum(n);
    rep(i,n){
        int c;
        cin>>c;
        cs.push(c);
        csum[i]=c;
    }
    sort(csum.begin(),csum.end());
    rep(i,n-1)csum[i+1]+=csum[i];
    queue<int> bfs;
    int ans[n];
    rep(i,n)ans[i]=-1;
    bfs.push(0);
    ans[0]=cs.top();
    cs.pop();
    while(!bfs.empty()){
        int now=bfs.front();
        bfs.pop();
        for(auto au:g[now]){
            if(ans[au]!=-1)continue;
            ans[au]=cs.top();
            cs.pop();
            bfs.push(au);
        }
    }
    cout<<csum[n-2]<<endl;
    rep(i,n){
        if(i)cout<<" ";
        cout<<ans[i];
    }
    cout<<endl;
}


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

#define ll long long int
#define ff first
#define ss second
#define pb push_back
#define MOD 1000000007
#define edl '\n'
#define IOFAST ios::sync_with_stdio(false);cin.tie(0); cout.tie(0);
#define PI 3.14159265
#define loop(i,n) for(ll i =0; i<n; i++)

#define vi vector<int>
#define vvi vector<vector<int>>
#define vvpii vector<vector<pair<int, int>>>
#define vpii vector<pair<int, int>>

int main(){
    ll x,k,d;
    cin>>x>>k>>d;

    x = abs(x);
    ll pos_c = x%d;
    ll neg_c = (x%d)-d;
    ll pos_steps = x/d;
    if (k>(ll)x/d){
        k -= x/d;
        if (k%2==0){
            cout <<pos_c;
        }
        else cout<<-neg_c;
    }
    else cout<<x-k*d;
}


Measured memory_bytes: 3632
//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("no-stack-protector")
//#pragma GCC push_options
//#pragma GCC optimize ("unroll-loops")
//#pragma GCC pop_options
//#pragma GCC target("popcnt")
//#pragma GCC target("sse4")
#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define rng(a) a.begin(),a.end()
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define rep(i, n) for (int i = 0; i < n; i++)
#define per(i, n) for (int i = n - 1; i > -1; i--)
#define rer(i, x, n) for (int i = x; i < n; i++)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef long double ld;













#define int long long

signed main(){
    ll n, a, b;
    cin >> n >> a >> b;
    if (a%2 == b%2){
        cout << (b - a) / 2;
        return 0;
    }
    if (a > b) swap(a, b);
    int r = a - 1;
    int bb = b;
    b -= r;
    b--;
    r++;
    r += (b - 1) / 2;
    int f = n - bb;
    a += f;
    a++;
    f++;
    f += (n - a) / 2;
    cout << min(r, f);



}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <vector>
#include <iostream>
#include<algorithm>
#include<string>
#include <map>
#include <queue>
#include <stack>

#define DIV 1000000007
using namespace std;

bool judge(vector<int> &per, vector<pair<int, int>> &edge) {
    int N = per.size() + 1;
    int M = edge.size();
    bool flag = 1;
    
    vector<int> junretu(N);
    junretu[0] = 1;
    for (int i = 0; i < N - 1; i++)
        junretu[i + 1] = per[i];
    for (int i = 0; i < N-1; i++) {
        for (int j = 0; j < M; j++) {
            if (junretu[i] == edge[j].first && junretu[i + 1] == edge[j].second) {
                break;
            }
            if (junretu[i + 1] == edge[j].first && junretu[i] == edge[j].second) {
                break;
            }
            if (j == M - 1) {
                flag = 0;
            }
        }
        if (!flag) break;
    }
    
    if (flag) {
        return true;
    }
    else {
        return false;
    }
}

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

    vector<pair<int, int>> edge(M);
    for (int i = 0; i < M; i++)
        cin >> edge[i].first >> edge[i].second;

    vector<int> per(N-1);
    for (int i = 0; i < N - 1; i++)
        per[i] = i + 2;

    int ans = 0;
    do {
        if (judge(per, edge) == true) {
            ans++;
        }
    } while (next_permutation(per.begin(), per.end()));

    cout << ans << endl;
}


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

public class Main {
    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        String next() {
            while (!st.hasMoreTokens())
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

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

        double nextDouble() {
            return Double.parseDouble(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        public long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++) a[i] = nextLong();
            return a;
        }
    }

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
       int n = sc.nextInt();
       String s = Integer.toString(n);
       if(s.charAt(0) == '9' || s.charAt(1) == '9'){
           System.out.println("Yes");
       }
       else{
           System.out.println("No");
       }
    }
}


Measured memory_bytes: 32728
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <vector>
#include <list>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <tuple>
using namespace std;

int main(){

    int n, k; cin >> n >> k;

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

    int temp;
    int ans = 1e9;
    for(int is=0; is<n-k+1; is++){
        // cout << is << endl;  
        if(x[is] >= 0){
            temp = x[is+k-1];
        }
        else if(x[is+k-1] <=  0){
            temp = abs(x[is]);
        }
        else if(x[is+k-1] >= abs(x[is])){
            // cout << x[is+k-1] << " " << x[is] << endl;
            temp = x[is+k-1] + 2*abs(x[is]);
        }
        else{
            // cout << x[is+k-1] << " " << x[is] << endl;
            temp = 2*x[is+k-1] + abs(x[is]);
        }
        
        if(temp < ans){
            ans = temp;
        }
    }

    cout << ans;

    return 0;
}

Measured memory_bytes: 640
import sys

from itertools import combinations


def solve(n, pairs):
    survivors = {v: {v} for v in range(1, n + 1)}
    for x, y in reversed(pairs):
        for v, srv in survivors.copy().items():
            if x in srv:
                if y in srv:
                    del survivors[v]
                else:
                    srv.add(y)
            elif y in srv:
                srv.add(x)
    return sum(su.isdisjoint(sv) for su, sv in combinations(survivors.values(), 2))


n, m = map(int, input().split())
pairs = [tuple(map(int, line.split())) for line in sys.stdin.readlines()]
print(solve(n, pairs))


Measured memory_bytes: 66012
def main():
    N = int(input())
    A = [input() for i in range(N)]
    if len(A) != len(set(A)):
        return print("No")
    pre = A[0][-1]
    for a in A[1:]:
        if pre != a[0]:
            return print("No")
        pre = a[-1]
    print("Yes")


if __name__ == '__main__':
    main()


Measured memory_bytes: 38256
#include<iostream>
#include<cstdio>
#include<cctype>
using namespace std;
int main(){
    char a;
    int i;
   
    while(1){
        
        scanf("%c",&a);
        
        
      
         if(islower(a)){
             printf("%c", toupper(a));
        }
        else if(isupper(a)){
            printf("%c", tolower(a));
        }
        
        else  {
            printf("%c",a);
            
        }
       if(a=='\n') break;
    }
    
    return 0;
}



Measured memory_bytes: 3132
import 'dart:io';

List dfs(n, m) {
  var ret = [];
  if (n == 1) {
    for (var i = 1; i <= m; i++) {
      ret.add([i]);
    }
  } else {
    for (var i = m; i > 0; i--) {
      //rint(ret);
      for (List<int> arr in dfs(n - 1, i)) {
        List tmp = arr + [i];
        ret.add(tmp);
      }
    }
  }
  //    print(ret);
  return (ret);
}

main(List<String> args) {
  List NMQ = stdin.readLineSync().split(" ").map((x) => int.parse(x)).toList();
  var abcd = []..length = NMQ[2];
  for (var i = 0; i < NMQ[2]; i++) {
    abcd[i] = stdin.readLineSync().split(" ").map((x) => int.parse(x)).toList();
  }
  var A = dfs(NMQ[0], NMQ[1]);
  var ans = 0;
  for (var arr in A) {
    var score = 0;
    for (var B in abcd) {
      if (arr[B[1] - 1] - arr[B[0] - 1] == B[2]) score += B[3];
    }
    if (score > ans) ans = score;
  }
  print(ans);
}


Measured memory_bytes: 107912
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rrep(i, n) for (int i = (n)-1; i >= 0; i--)
using llong = long long;
using P = pair<int, int>;
const int inf = 1 << 20;
const int mod = 1e9 + 7;

int main() {
   string s, t;
   int a, b;
   cin >> s >> t;
   cin >> a >> b;
   string u;
   cin >> u;
   if (s == u)
      a--;
   if (t == u)
      b--;
   printf("%d %d\n", a, b);
   return 0;
}

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

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

    if (s[s.length() - 1] != 's') {
        cout << s + 's';
    }
    else if (s[s.length() - 1] == 's') {
        cout << s + "es";
    }
}

Measured memory_bytes: 3136
N = int(input())
A = list(map(int, input().split()))

stock = 0
money = 1000
for i in range(N-1):
    if A[i+1] >= A[i]:
        stock += money // A[i]
        money = money % A[i]
    else:
        money += stock * A[i]
        stock = 0

ans = money + stock * A[-1]
print(ans)


Measured memory_bytes: 9100
#![allow(unused_imports)]
#![allow(dead_code)]
#![macro_use]
use std::io::prelude::*;
use std::cmp::{max, min};
use std::collections::{HashSet, HashMap, BinaryHeap};

const MOD: i64 = 1e9 as i64 + 7;

macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn gcd(x: usize, y: usize)->usize{
    if y == 0{
        return x
    }
    gcd(y, x % y)
}

fn main() {
    input! {
        n: usize,
        sp: [(String, isize); n],
    }
    let mut a: Vec<(&str, isize, usize)> = vec![("", 0, 0);n];
    for i in 0..n {
        a[i].0 = &sp[i].0;
        a[i].1 = -sp[i].1;
        a[i].2 = i + 1;
    }
    a.sort();
    for i in a.iter(){
        println!("{}", i.2);
    }
}


Measured memory_bytes: 4352
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
#define rep(i,n) for(ll i=0;i<n;++i)
#define ocut cout
#define ouct cout
#define itn int

struct Union{
  vector<ll> par;
  Union(ll a){
  par=vector<ll>(a,-1);
  }
  ll find(ll a){
    if(par[a]<0){
      return a;
    }
    else{
      return par[a]=find(par[a]);
    }
  }
  bool same(ll a,ll b){
    return (find(a)==find(b));
  }
  ll size(ll a){
    return -par[find(a)];
  }
  void unite(ll a,ll b){
    ll c=find(a),d=find(b);
    if(c==d)
      return;
    if(size(c)<size(d)){
      swap(c,d);
    }
    par[c]+=par[d];
    par[d]=c;
  }
};
int gcd(int a, int b)
{
   if (a%b == 0)
   {
       return(b);
   }
   else
   {
       return(gcd(b, a%b));
   }
}

int main(){
  ll n,x;
  cin >> n >> x;
  ll a[n],k;
  rep(i,n){
      cin >> a[i];
      if(i==0)k=a[0]-x;
      a[i]-=x;
      k=gcd(k,a[i]);
  }
  cout << abs(k);
}

Measured memory_bytes: 1024
import java.util.Scanner;

public class Main {
	static final long MOD = 1_000_000_007L;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		System.out.println(n / 2 + n % 2);
		
		sc.close();
	}

}






Measured memory_bytes: 21716
#include <bits/stdc++.h>
using namespace std;
#define INF 2000000000
typedef long long int ll;
typedef pair<ll,ll> ii;
typedef pair<ii,ll> iii;
typedef vector<ll> vi;
typedef vector<ii> vii;
#define getbit(n,i) (((n)&(1<<(i)))!=0)
#define setbit0(n,i) ((n)&(~(1<<(i))))
#define setbit1(n,i) ((n)|(1<<(i)))
#define togglebit(n,i) ((n)^(1<<(i)))
#define lastone(n) ((n)&(-(n)))
#define read freopen("debug\\in.txt","r",stdin)
#define write freopen("debug\\out.txt","w",stdout)
#define fi first
#define se second
#define getI(a) scanf("%d",&a)
#define getII(a,b) scanf("%d%d",&a,&b)
#define PI (acos(-1))
#define fastread ios_base::sync_with_stdio(false);cin.tie(NULL)
#define mod (1000000007)
#define asz 500005
#define pb push_back
#define ppf pop_front
#define ppb pop_back
#define pf push_front
   
int main()
{
    fastread;
    string s;
    ll i,j,k,l,n,m;
    cin>>s;
    ll a=0;
    ll b=0;
    for(i=0;i<3;i++){
    	if(s[i]=='A')
    	a++;
    	else
    	b++;
	}
	if(a>0&&b>0)
	cout<<"Yes";
	else
	cout<<"No";
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int main(){
  int64_t n,k,i,i1,i2;
  cin>>n>>k;
  vector<int64_t> a(n),b(n+1);
  set<int64_t> s;
  for(i=0;i<n;i++) cin>>a.at(i);
  for(i=0;i<=n;i++){
    if(i==0) b.at(i)=1;
    else b.at(i)=a.at(b.at(i-1)-1);
    if(s.count(b.at(i))) break;
    else s.insert(b.at(i));
  }
  i2=i;
  for(i1=0;i1<i2;i1++) if(b.at(i1)==b.at(i2)) break;
  if(k<i1) cout<<b.at(k)<<endl;
  else{
    i=(k-i1)%(i2-i1)+i1;
    cout<<b.at(i)<<endl;
  }
}

Measured memory_bytes: 15512
#include<bits/stdc++.h>
using namespace std;
#define ll long long
map<pair<ll,ll>,ll> mp1;
vector<vector<ll> > vec(52),edj(52);
vector<ll> path;
ll arr[52],dp[52][2097155],n,f,visit[52],m;
void dfs(ll x,ll y)
{
    path.push_back(x);
    if(x==y)
    {
        f=1;
        return;
    }
    for(auto it=vec[x].begin();it!=vec[x].end();it++)
    {
        if(visit[*it]==0 && f==0)
        {
            visit[*it]=1;
            dfs(*it,y);
        }
    }
    if(f==0)
        path.pop_back();
}
ll rec(ll i,ll mask)
{
    if(i==n)
    {
        if(mask==((1<<(m))-1))
            return 1;
        else
            return 0;
    }
    if(dp[i][mask]!=-1)
        return dp[i][mask];
    return dp[i][mask]=rec(i+1,mask)+rec(i+1,mask|arr[i]);
}
int main()
{
    ll i,x,y,j;
    cin>>n;
    for(i=1;i<n;i++)
    {
        cin>>x>>y;
        vec[x].push_back(y);
        vec[y].push_back(x);
        mp1[{x,y}]=i;
        mp1[{y,x}]=i;
    }
    cin>>m;
    for(i=1;i<=m;i++)
    {
        cin>>x>>y;
        visit[x]=1;
        dfs(x,y);
        for(j=1;j<=n;j++)
            visit[j]=0;
        f=0;
        for(auto it=path.begin()+1;it!=path.end();it++)
        {
            auto it1=it-1;
            edj[mp1[{*it,*it1}]].push_back(i);
        }
        path.clear();
    }
    for(i=0;i<=50;i++)
    {
        for(j=0;j<=2097154;j++)
        {
            dp[i][j]=-1;
        }
    }
    for(i=1;i<n;i++)
    {
        ll s=0;
        for(auto it=edj[i].begin();it!=edj[i].end();it++)
            s+=(1<<((*it)-1));
        arr[i]=s;
    }
    cout<<rec(1,0);
}


Measured memory_bytes: 837888
class dice():
    
    def __init__(self,a,b,c,d,e,f):
        self.A=[a,b,c,d,e,f]
        self.temp=[]
        
    def q_method(self,x,y):
       for i in self.A:
        self.temp.append(i)       

        #xとyが何番目の配列かを確認する
        n=self.A.index(x)
        m=self.A.index(y)

       if n==0:
           if m==1:
               print(self.A[2])
           elif m==2:
               print(self.A[4])
           elif m==3:
               print(self.A[1])
           elif m==4:
               print(self.A[3])
       elif n==1:
           if m==0:
              print(self.A[3])
           elif m==2:
              print(self.A[0])
           elif m==3:
              print(self.A[5])
           elif m==5:
               print(self.A[2])
       elif n==2:
           if m==0:
               print(self.A[1])
           elif m==1:
               print(self.A[5])
           elif m==4:
               print(self.A[0])
           elif m==5:
               print(self.A[4])
       elif n==3:
           if m==0:
               print(self.A[4])
           elif m==1:
               print(self.A[0])
           elif m==4:
               print(self.A[5])
           elif m==5:
               print(self.A[1])

       elif n==4:
           if m==0:
               print(self.A[2])
           elif m==2:
               print(self.A[5])
           elif m==3:
               print(self.A[0])
           elif m==5:
               print(self.A[3])
       elif n==5:
           if m==1:
               print(self.A[3])
           elif m==2:
               print(self.A[1])
           elif m==3:
               print(self.A[4])
           elif m==4:
               print(self.A[2])

       
       
if __name__=="__main__":

    input_text=""
    input_text=input()
    array=[]
    array=input_text.split()

    ob1=dice(array[0],array[1],array[2],array[3],array[4],array[5])

    question=input()
    question=int(question)

    for i in range(question):
        input_order=input()

        order_array=[]
        order_array=input_order.split()
        ob1.q_method(order_array[0],order_array[1])



Measured memory_bytes: 5620
strlen = int(input())
stamp_book = input()

MARU = "O"
BATSU = "X"

count = 0
index = 0

while True:
    if (index + 1) >= strlen:
        break

    if stamp_book[index] != stamp_book[index + 1]:
        count += 1
        index += 2
    else:
        index += 1

print(count)


Measured memory_bytes: 5788
n,m=map(int,input().split())
branch=[tuple(map(int,input().split())) for _ in range(m)]
res=[0]
data=[-1 for _ in range(1+n)]
def calc(k):
    k=abs(k)
    return 1/2*k*(k-1)

def search(data,x):
    if data[x]<=0:
        return x
    else:
        data[x]=search(data,data[x])
    return data[x]

for i in range(m):
    a,b=branch.pop()
    aroot=search(data,a)
    broot=search(data,b)
    if aroot==broot:
        res.append(res[-1])
        continue
    res.append(res[-1]-calc(data[aroot])-calc(data[broot])+calc(data[aroot]+data[broot]))
    if data[aroot]<=data[broot]:
        data[aroot]+=data[broot]
        data[broot]=aroot
    elif data[aroot]>data[broot]:
        data[broot]+=data[aroot]
        data[aroot]=broot
for j in range(m-1,-1,-1):
    print(int(res[m]-res[j]))        

Measured memory_bytes: 18576
#include <bits/stdc++.h>
#define fi first
#define se second
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define rng(a) a.begin(),a.end()
#define sz(x) (int)(x).size()
#define uni(x) x.erase(unique(rng(x)),x.end())
#define show(x) cout<<#x<<" = "<<x<<endl;
#define PQ(T) priority_queue<T,v(T),greater<T> >
#define newline puts("")
#define v(T) vector<T>
#define vv(T) v(v(T))
#define chmin(x,y) x=min(x,y)
#define chmax(x,y) x=max(x,y)
#define EPS (1e-10)
#define equals(a, b) (fabs((a)-(b)) < EPS)
using namespace std;
typedef long long int ll;
typedef pair<int,int> P;
typedef set<int> S;
typedef queue<int> Q;
typedef queue<P> QP;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;
const ll LINF = 1001002003004005006ll;
const int INF = 1001001001;
const int MOD = 1000000007;
  
int main() {
  string s;
  cin >> s;
  string ans = "";
  for(char c:s) {
    switch(c) {
      case '0':
        ans += '0';
        break;
      case '1':
        ans += '1';
        break;
      case 'B':
        if(ans.empty()) break;
        ans.pop_back();
        break;
    }
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 3632
#include<bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define rrep(i,n) for(int i=1,i##_len=(n); i<=i##_len; ++i)
#define drep(i,n) for(int i=(n)-1; i>=0; --i)
#define srep(i,s,t) for(int i=(s);i<(t);++i)
#define rng(obj) (obj).begin(), (obj).end()
#define maxs(x,y) (x=max((x),(y)))
#define mins(x,y) (x=min((x),(y)))
#define limit(x,l,r) max(l,min(x,r))
#define lims(x,l,r) (x=max(l,min(x,r)))
#define isin(x,l,r) ((l) <= (x) && (x) < (r))
#define pb push_back
#define sz(x) (int)(x).size()
#define uni(x) x.erase(unique(rng(x)),x.end())
#define show(x) cout<<#x<<" = "<<x<<endl;
#define PQ(T) priority_queue<T,v(T),greater<T>>
#define bn(x) ((1<<x)-1)
#define dup(x,y) (((x)+(y)-1)/(y))
#define newline puts("")
#define v(T) vector<T>
#define vv(T) vector<vector<T>>
using ll = long long;
using ull = unsigned long long;
using uint = unsigned int;
using P = pair<int,int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vp = vector<P>;
template <class T> inline istream& operator>>(istream&i,v(T)&v)
{ rep(j,sz(v))i>>v[j];return i;}
template <class T> string join(const v(T)&v)
{ stringstream s;rep(i,sz(v))s<<' '<<v[i];return s.str().substr(1);}
template <class T> inline ostream& operator<<(ostream&o,const v(T)&v)
{ if(sz(v))o<<join(v); return o;}
template <class T1,class T2> inline istream& operator>>(istream&i ,pair<T1,T2>&v)
{ return i>>v.fi>>v.se;}
template <class T1,class T2> inline ostream& operator<<(ostream&o ,pair<T1,T2>&v)
{ return o<<v.fi<<","<<v.se;}
template <class T> inline ll suma(const v(T)& a) 
{ ll res(0); for(auto&& x:a) res += x; return res;}
const int INF = 1001001001;
const ll LINF = 1001002003004005006ll;
const double eps = 1e-10;
const int MX = 200005;
//----------------------------------------------------------------

#define fileio ifstream fio; if(argc>=2){fio.open(argv[1]); std::cin.rdbuf(fio.rdbuf());}
#define fastio ios_base::sync_with_stdio(false);
#define MOD 1000000007
//----------------------------------------------------------------

void Main(){
  int n;
  cin>>n;
  vl a(n);
  cin>>a;
  unordered_map<ll,ll> m;
  rep(i,n){
    m[a[i]]++;
  }
  ll ans = 0;
  for(auto i:m){
    if(i.se>i.fi) ans+=i.se-i.fi;
    else if(i.se<i.fi) ans+=i.se;
  }
  cout<<ans<<endl;
} int main(int argc,char* argv[]){ 
    fastio; fileio; Main();}

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

namespace atcorder_ExaWizards_2019
{
    class Program
    {

        static void Main(string[] args)
        {

            int cnt = int.Parse(Console.ReadLine());
            var strArr = Console.ReadLine().ToArray();

            int cntR = 0;
            int cntB = 0;

            for (int i = 0; i < cnt; i++)
            {
                if ('R' == strArr[i]) cntR++;
                else cntB++;
            }

            string ret = "No";
            if (cntB < cntR) ret = "Yes";

            Console.WriteLine(ret);

        }
    }
}



Measured memory_bytes: 11220
#define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define ALL(v) v.begin(), v.end()
typedef long long ll;

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; }

#include <bits/stdc++.h>
using namespace std;

int main() {
  int n;
  cin>>n;
  
  vector<int> v(n),c(n);
  rep(i,n) cin>>v[i];
  rep(i,n) cin>>c[i];
  
  int ans=0;
  rep(i,n){
    if(v[i]>c[i]){
      ans+=v[i]-c[i];
    }
  }
  
  cout<<ans<<endl;
  
  return 0;
}

Measured memory_bytes: 256
// Problem : C - Multiple Gift
// Contest : AtCoder Regular Contest 088
// URL : https://atcoder.jp/contests/arc088/tasks/arc088_a
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include "bits/stdc++.h"
using namespace std;
using ll = long long;
#define cerr if(1)cerr
#define size(x) (int)x.size()
#define all(x) x.begin(), x.end()

const int N = 1e6 + 1, mod = 1e9 + 7, inf = 2e9;

ll x, y;

int main() { cin.tie(0)->sync_with_stdio(0);
	cin >> x >> y;
	cout << int(__lg(y / x)) + 1;
}


Measured memory_bytes: 256
def main():
    n = int(input())
    d = list(map(int, input().split()))
    d.sort()

    avr = len(d)//2 - 1
    if d[avr] == d[avr+1]:
        print(0)
    else:
        res = [i for i in range(d[avr]+1,d[avr+1]+1)]
        print(len(res))


if __name__ == '__main__':
    main()

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

using namespace std;

using ll = long long;
using ld = long double;
using P = pair<int, int>;
constexpr ld EPS = 1e-12;
constexpr int INF = numeric_limits<int>::max() / 2;
constexpr int MOD = 1e9 + 7;

template <typename T>
void printv(const vector<T> &v)
{
    int sz = v.size();
    for (int i = 0; i < sz; i++)
    {
        cout << v[i] << " \n"[i == sz - 1];
    }
}

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

    double t, x;
    cin >> t >> x;
    cout << fixed << setprecision(10) << t / x << endl;
}


Measured memory_bytes: 256
x1,y1,x2,y2 = map(int,input().split())
t = x2-x1
s = y2-y1
x3 = x2-s
y3 = y2 + t
x4 = x1-s
y4 = y1 + t
print("{} {} {} {}".format(x3,y3,x4,y4))

Measured memory_bytes: 2940
#include <iostream>
#include <vector>
using namespace std;
int n;
long long a[300000];
long long o[100];
long long x[100];
long long mod=1e9+7;
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
		for(int j=0;j<60;j++){
			if(a[i]&(1LL<<j)){
				o[j]++;
			}else{
				x[j]++;
			}
		}
	}
	long long ans=0;
	for(int i=0;i<60;i++){
		(ans+=(((o[i])*(x[i])%mod)*((1LL<<i)%mod))%mod)%=mod;
	}
	cout<<ans<<endl;
	return 0;
}



Measured memory_bytes: 2560