akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <map>
using namespace std;

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

    long long A[N];

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

    sort(A, A+N, greater<int>());

    long long longBar = 0;
    long long shortBar = 0;
    for(int i=1;i<N;i++){
        if(longBar == 0){
            if(A[i-1] == A[i]){
//                cout << A[i-1] << endl;
                longBar = A[i-1];
                i++;
            }
        }else{
            if(A[i-1] == A[i]){
 //               cout << A[i-1] << endl;
                shortBar = A[i-1];
                break;
            }
        }
    }
    long long res = longBar * shortBar;
    cout << res << endl;
}

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

#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep1(i, n) for (int i = 1; i < (int)(n); i++)
typedef long long ll;

int main() {
    int k,x; cin >> k >> x;
    if(500*k >= x){
        cout << "Yes" << endl;
    }else{
        cout << "No" << endl;
    }
}

Measured memory_bytes: 256
/*
[yahoo-procon2019-qual] C - When I hit my pocket...
*/

#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long int ll;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;

ll K, A, B;

ll solve() {
    return max(K + 1, (K - A + 1) / 2 * (B - A) + A + (K - A + 1) % 2);
}

int main() {
    cin >> K >> A >> B;

    cout << solve() << endl;

    return 0;
}


Measured memory_bytes: 256
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 21:05:44 2020

@author: NEC-PCuser
"""
X, Y = map(int, input().split())

max_fit = X * 2
min_fit = X * 4

if (Y % 2 == 0 and max_fit <= Y and min_fit >= Y):
    print("Yes")
else:
    print("No")


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

using namespace std;
using LL = long long;
using P = pair<int,int>;
const int kind=26;
const int INF=1e9;
const int max_queries=5e4;

int main(){
	int D;
	cin >> D;
	vector<int> c(kind);
	rep(i,kind) cin >> c[i];
	int c_sum=0;
	rep(i,kind) c_sum+=c[i];
	vector<vector<int>> s(D,vector<int>(kind));
	rep(i,D){
		rep(j,kind) cin >> s[i][j];
	}
	vector<int> t(D), max_score(D,-INF);
	vector<int> last(kind);
	int dec=0;
	for(int day=1; day<=D; day++){
		int k=-1;
		dec+=c_sum;
		rep(i,kind){
			int res=s[day-1][i];
			res-=dec;
			res+=c[i]*(day-last[i]);
			if(res>max_score[day-1]){
				max_score[day-1]=res;
				k=i;
			}
		}
		dec-=c[k]*last[k];
		last[k]=day;
		t[day-1]=k;
	}
	/*
	vector<set<int>> hold(kind);
	rep(i,kind) hold[i].insert(0);
	rep(i,D) hold[t[i]].insert(i+1);
	*/
	int M=max_queries;
	vector<int> d(M), q(M);
	q[0]=t[0];
	vector<int> t_new(D);
	rep(i,D) t_new[i]=t[i];
	int fin_score=0;
	rep(i,M){
		int ch_ans=0, ch_dec=0;
		vector<int> ch_last(kind);
		set<P> change;	
		t_new[d[i]]=q[i];
		for(int day=1; day<=D; day++){
			int k=t_new[day-1];
			ch_ans+=s[day-1][k];
			ch_dec+=c_sum;
			ch_ans-=ch_dec;
			ch_ans+=c[k]*(day-ch_last[k]);
			ch_dec-=c[k]*(day-ch_last[k]);
			int tot=s[day-1][k]-ch_dec;
			change.insert(P(tot,day-1));
			ch_last[k]=day;
		}
		if(fin_score>=ch_ans){
			t_new[d[i]]=t[d[i]];
		}
		else{
			fin_score=ch_ans;
			/*
			hold[t[d[i]]].erase(d[i]+1);
			hold[q[i]].insert(d[i]+1);
			*/
		}
		if(i!=M-1){
			auto itr=change.begin();
			int r=rand()%20, plus=0;
			if(r<=10) plus=0;
			else if (r<=15) plus=1;
			else if (r<=17) plus=2;
			else if (r<=18) plus=3;
			else plus=4;
			rep(j,plus) itr++;
			d[i+1]=itr->second;
			/*
			int res=-INF, n=-1;
			rep(j,kind){
				auto itr=hold[j].upper_bound(d[i+1]);
				itr--;
				int prev=*itr;
				int dif=c[j]*((d[i+1]+1)-prev);
				if(res<dif){
					res=dif;
					n=j;
				}
			}
			q[i+1]=n;
			*/
			q[i+1]=rand()%26;
		}
	}
	rep(i,D) cout << t_new[i]+1 << endl;

	return 0;
}

Measured memory_bytes: 3720
// AOJ 2386: Sightseeing Tour
// 2018.1.2 bal4u@uu

#include <stdio.h>

int map[102][102];

//#define getchar_unlocked()  getchar()
int in()
{
	int n, c;

	while ((c = getchar_unlocked()) < '0');
	n = 0;
	do n = (n<<3)+(n<<1) + (c & 0xf), c = getchar_unlocked();
	while (c >= '0');
	return n;
}

int main()
{
	int n, r, c, x;
	long long ans;

	n = in();
	for (r = 0; r < n; r++) for (c = 0; c < n; c++) map[r][c] = in();

	ans = 0;
	for (r = 0; r < n; r++) for (c = r+1; c < n; c++) {
		x = map[r][c];
		if (x > map[c][r]) x = map[c][r];
		ans += x;
	}
	printf("%lld\n", ans);
	return 0;
}



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

using namespace std;

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int K, S;
	cin >> K >> S;
	int ans = 0;
	for (int x = 0; x <= K; x++) {
		for (int y = 0; y <= K; y++) {
			int z = S - x - y;
			ans += (z >= 0 && z <= K);
		}
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 256
N=int(input())
H=list(map(int,input().split()))
C=0
for i in range(N-1):
    if C>=2:
        break
    elif H[i]>H[i+1]+1:
        C=C+2
        break
    elif H[i]>H[i+1]:
        C=C+1
    elif H[i]<H[i+1]:
        C=0
if C<2:
    print('Yes')
else:
    print('No')

Measured memory_bytes: 14836
#include<bits/stdc++.h>
using namespace std;
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define ALL(A) A.begin(),A.end()
#define RALL(A) A.rbegin(),A.rend()
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 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
const LL mod=1000000007;
const LL LINF=1LL<<62;
const int INF=1<<30;
int dx[]={1,0,-1,0,1,-1,1,-1};
int dy[]={0,1,0,-1,1,-1,-1,1};



int main(){
    int n;cin >> n;
    vector<LL> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    vector<vector<LL>> dp(n, vector<LL> (3, -LINF));
    if(n%2){
        dp[0][0] = a[0];
        dp[1][1] = a[1];
        dp[2][2] = a[2];
        for (int i = 0; i < n; i++) {
            if(i+2<n){
                chmax(dp[i+2][0],dp[i][0]+a[i+2]);
                chmax(dp[i+2][1],dp[i][1]+a[i+2]);
                chmax(dp[i+2][2],dp[i][2]+a[i+2]);
            }
            if(i+3<n){
                chmax(dp[i+3][2],dp[i][1]+a[i+3]);
                chmax(dp[i+3][1],dp[i][0]+a[i+3]);
            }
            if(i+4<n){
                chmax(dp[i+4][2],dp[i][0]+a[i+4]);
            }
        }
        cout << max({dp[n-1][2],dp[n-2][1],dp[n-3][0]}) << endl;
    }
    else{
        dp[1][1] = a[1];
        dp[0][0] = a[0];
        for (int i = 0; i < n; i++) {
            if(i+2<n){
                chmax(dp[i+2][1],dp[i][1]+a[i+2]);
                chmax(dp[i+2][0],dp[i][0]+a[i+2]);
            }
            if(i+3<n) chmax(dp[i+3][1],dp[i][0]+a[i+3]);
        }
        cout << max(dp[n-1][1],dp[n-2][0]) << endl;
    }
    return 0;
}



Measured memory_bytes: 15644
n=int(input())
a=list(map(int,input().split()))
a.sort()
num1=a[0]
num2=1
ans=0
for i in range(n-1):
    if num1==a[i+1]:
        num2+=1
    else:
        if num2<num1:
            ans+=num2
        else:
            ans+=num2-num1
        num1=a[i+1]
        num2=1
if num2>1:
    if num2<num1:
        ans+=num2
    else:
        ans+=num2-num1
else:
    if num1>1:
        ans+=1
print(ans)


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

using namespace std;
typedef long long int ll;
typedef pair<ll, ll > pi;  
typedef pair<pair<ll, ll >, ll > pii;  
vector<ll > vec;
vector<vector<ll > > vec2;
ll MOD = 1000000007;
ll INF = 1145141919454519;

int main() {

    ll N, M; cin >> N >> M;

    ll ans = 0;
    if(M - N * 2 >= 0){
        ans += N;
        M = M - ans * 2;
        ans += M / 4;
    }else{
        ans += M / 2;
        M = M - ans * 2;
    }

    cout << ans << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
// #include <ext/pb_ds/assoc_container.hpp>
// #include <ext/pb_ds/tree_policy.hpp>
 
// using namespace __gnu_pbds;
using namespace std;
 
// template <typename T>
// using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
 
typedef long long ll;
typedef long double ld;
typedef pair <long long,long long> ii;
typedef complex<long double> point;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll n;
    cin >> n;
    cout << n*n*n << endl;
}

Measured memory_bytes: 256
#include<iostream>
using namespace std;
int main() {
    int n, v, j;
    cin >> n;
    int A[n];
    for (int i=0; i<n; i++){
        cin >> A[i];
    }
    for (int i=0; i<n; i++){
        if (i == n-1){
            cout << A[i] << endl;
        } else {
            cout << A[i] << " ";
        }
    }
    for (int i=1; i<n; i++){
        v = A[i];
        j = i-1;
        while (j>=0 && A[j]>v){
            A[j+1] = A[j];
            j--;
        }
        A[j+1] = v;
        for (int j=0; j<n; j++){
            if (j == n-1){
                cout << A[j] << endl;
            } else {
                cout << A[j] << " ";
            }
        }
    }
    return 0;
}


Measured memory_bytes: 3080
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <string>

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
#define REP(i, n) for (int i = 0; i < (n); i++)
#define RREP(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define RFOR(i, a, b) for (int i = (a); i > (b); i--)
#define ALL(a) (a).begin(), (a).end()

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

    int ans = 0;
    FOR(i, A, B + 1) {
        string num = to_string(i);
        string r_num = to_string(i); reverse(ALL(r_num));
        if (num == r_num) ans++;
    }
    cout << ans << endl;
    return 0;
}

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

using namespace std;

typedef long long ll;
const int N = 100001;
const int MOD = 1e9 + 7;
signed main()
{
//  freopen("in.txt", "r", stdin);
//  freopen("out.txt", "w", stdout);
  int n;
  string s;
  cin >> n >> s;
  int cnt[26] = {0};
  for(int i = 0;i < n;i++)
    cnt[s[i] - 'a']++;
  ll res  = 1;
  for(int i = 0;i < 26;i++)
    res = res * (cnt[i] + 1) % MOD;
  cout << res - 1;
  return 0;
}


Measured memory_bytes: 512
import collections
N, M = map(int, input().split())
dic = {i + 1: set() for i in range(N)}

for m in range(M):
    A, B = map(int, input().split())
    dic[A].add(B)
    dic[B].add(A)


vi_n = [i + 1 for i in range(N)]
vi_d = set()
stack = [i+1 for i in range(N)]
while (len(vi_d) < N):
    v = stack.pop()
    if v in vi_d:
        continue
    vi_d.add(v)

    for node in dic[v]:
        stack.append(node)
        vi_n[node - 1] = vi_n[v - 1]


c = collections.Counter(vi_n)
c_l = list(c.values())
#print(c_l)
print(max(c_l))
    


    




Measured memory_bytes: 177768
import sys, math

def input():
    return sys.stdin.readline()[:-1]

def main():
    a, b, x = map(int,input().split())
    t = a//x
    s = b//x
    if a%x == 0:
        print(s-t+1)
    else:
        print(s-t)

if __name__ == '__main__':
    main()


Measured memory_bytes: 38384
/**
 *      ABC 76 A
 *      author  : kyomukyomupurin
 *      created : 2018-09-04 16:45:52
**/

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

int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    int R, G; cin >> R >> G;
    cout << 2 * G - R << endl;

    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define sync ios_base::sync_with_stdio(false), cin.tie(NULL)
#define F first
#define S second
#define pb emplace_back
#define mt make_tuple
#define gcd __gcd
#define PI 3.141592653589
// Input
#define in(a) scanf("%d",&a)
#define in2(a,b) scanf("%d%d",&a,&b)
#define in3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define llin(a) cin >> a
#define inl(a) scanf("%lld",&a)
#define read(v,i,n) for(i=0;i<n;i++)in(v[i])
#define twod(mat,i,j,n,m) rep(i,n){rep(j,m)in(mat[i][j]);}
#define sc(ch) scanf("%c",&ch)
#define sstr(str) scanf("%s",str)
// Output
#define pr(a) printf("%d ",a)
#define pr2(a,b) printf("%d %d\n",a,b)
#define pr3(a,b,c) printf("%d %d %d\n",a,b,c)
#define out(a) printf("%d\n",a)
#define outl(a) printf("%lld\n",a)
#define llpr(a) cout << a << " "
#define llout(a) cout << a << "\n"
#define yes printf("YES\n")
#define no printf("NO\n")
#define lin printf("\n")
// Iterator
#define lp(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) for(i=0;i<n;i++)
#define all(vec) vec.begin(),vec.end()
#define lower(v,k) lower_bound(v.begin(),v.end(),k)-v.begin()
#define upper(v,k) upper_bound(v.begin(),v.end(),k)-v.begin()
#define tf(mytuple) get<0>(mytuple)
#define ts(mytuple) get<1>(mytuple)
#define tt(mytuple) get<2>(mytuple)
// Debug
#define dbg(v,i,n) for(i=0;i<n;i++)pr(v[i]); lin
#define what(x) cerr << #x << " : " << x << "\n"
#define ck printf("continue\n")
#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args)
{
	cerr << *it << " = " << a << "\n";
	err(++it, args...);
}
// Data Type
#define ll long long int
#define ii pair<int,int>
#define pli pair<ll,int>
#define triple tuple<int,int,int>
#define vi vector<int>
#define vii vector<pair<int,int> >
#define vvi vector<vector<int> >
#define viii vector<pair<pair<int,int>,int> >
#define vvii vector<vector<pair<int,int> > >
#define M 998244353
#define N 100005  //check the limits, man
int main()
{
    int n,m,h,w,a;
    in2(n,m);
    in2(h,w);
    a=h*m+w*n-h*w;
    out(n*m-a);
}





Measured memory_bytes: 256
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.TreeMap;

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

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(br.readLine());

        Map<String, Integer> map = new TreeMap<>();

        for (int i = 0; i < n; i++) {
            String s = br.readLine();
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }

        int m = Integer.parseInt(br.readLine());

        for (int i = 0; i < m; i++) {
            String s = br.readLine();
            if (map.containsKey(s)) {
                map.put(s, map.get(s) - 1);
            } else {
                map.put(s, -1);
            }
        }

        br.close();

        int max = 0;
        for (var entry : map.entrySet()) {
            max = Math.max(max, entry.getValue());
        }

        bw.write(String.valueOf(max));

        bw.flush();

    }
}

Measured memory_bytes: 33008
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> l_l;
typedef vector<int> vei;
typedef vector<vector<int>> ve_vei;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<(int)(n);i++)
#define fs first
#define sc second
#define EPS (1e-7)
#define INF (1e9)
#define PI (acos(-1))
 
int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

    int N; cin >> N;
    vei p(N); rep(i,N) cin >> p[i];

    int sum = accumulate(p.begin(), p.end(), 0);
    int maxp = *max_element(p.begin(),p.end());
    cout << sum - (maxp / 2) << endl;
    }

Measured memory_bytes: 384
from fractions import gcd  # for python3.5~ use math.gcd


def main():
    N, X = list(map(int, input().split(' ')))
    x_list = list(map(lambda x: abs(int(x) - X), input().split(' ')))
    ans = x_list[0]
    for x in x_list[1:]:
        ans = gcd(ans, x)
    print(ans)


if __name__ == '__main__':
    main()

Measured memory_bytes: 16304
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <array>
#include <cmath>

using namespace std;

using ll = long long int;

int main() {

    int A, B;
    cin >> A >> B;

    if (A > B) {
        cout << A + A -1;
    } else if (A == B) {
        cout << A + A;
    } else {
        cout << B + B -1;
    }


    return 0;
}



Measured memory_bytes: 256
#include<iostream>
using namespace std;
int main()
{
 ios_base::sync_with_stdio(false);
 std::cin.tie(NULL);
 std::cout.tie(NULL);
  long long int N,R;
  cin>>N>>R;
  long long int I;
  if(N>=10)
  {
    I=R;
    cout<<I<<endl;
  }
  else
  {
    I=R+100*(10-N);
    cout<<I<<endl;
  }
  
 
  
  
  
  
 return 0;
}

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

using ll = long long;
#define FOR(i, m, n) for (int i = (m); i < (n); i++)
#define REP(i, n) FOR(i, 0, n)
#define ALL(c) (c).begin(), (c).end()
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;}
const int MOD = 1000000007;

int main() {
    int n, l;
    cin >> n >> l;
    vector<ll> a(n, 0);
    ll p, x;
    ll ml = 0;
    ll mi = 0;
    cin >> p;
    FOR(i, 1, n) {
        cin >> x;
        a[i] = p + x;
        if (ml < a[i]) {
            ml = a[i];
            mi = i;
        }
        p = x;
    }
    if (ml < l) {
        cout << "Impossible" << endl;
    } else {
        cout << "Possible" << endl;
        FOR(i, 1, mi) {
            cout << i << endl;
        }
        for (int i = n - 1; i > mi; i--) {
            cout << i << endl;
        }
        cout << mi << endl;
    }
}


Measured memory_bytes: 1664
#include <bits/stdc++.h>
using namespace std;
using pint = pair<int,int>;

const long long INFLL = 1LL << 60;
const int INFI = 1000000000;


int main() {
    long long A, B, C; cin >> A >> B >> C;
    if (A % 2 == 0 || B % 2 == 0 || C % 2 == 0) cout << 0 << endl;
    else cout << min({A*B, B*C, C*A}) << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#define rep(i,n) for(int i=0;i<n;++i)
using namespace std;

int main() {
	int n, T; cin >> n >> T;
	vector<int> c(n);
	vector<int> t(n);
	rep(i, n) cin >> c[i] >> t[i];
	int minc = 1e9;
	int count = 0;
	rep(i, n) {
		if (t[i] <= T) {
			minc = min(minc, c[i]);
			count++;
		}
	}
	(count == 0) ? cout << "TLE" << endl : cout << minc << endl;
	return 0;
}



Measured memory_bytes: 256
x, n = map(int, input().split())
p = list(map(int, input().split()))
flag = [False] * 102
for value in p:
    flag[value] = True
minAbs = 200
for i in range(102):
    ab = abs(x - i)
    if not flag[i]:
        minAbs = min(minAbs, ab)
for i in range(102):
    ab = abs(x - i)
    if not flag[i] and ab == minAbs:
        print(i)
        break

Measured memory_bytes: 9204
import sys,os
from collections import defaultdict, deque
from math import ceil, floor
if sys.version_info[1] >= 5:
    from math import gcd
else:
    from fractions import gcd
sys.setrecursionlimit(10**6)
write = sys.stdout.write
dbg = (lambda *something: print(*something)) if 'TERM_PROGRAM' in os.environ else lambda *x: 0
def main(given=sys.stdin.readline):
    input = lambda: given().rstrip()
    LMIIS = lambda: list(map(int,input().split()))
    II = lambda: int(input())
    MOD = 10**9+7

    A,B,C,K = LMIIS()
    
    if A >= K:
        print(K)
        return 


    if A+B >= K:
        print(A)
        return
    

    m = K-(A+B)
    print(A-m)

    

if __name__ == '__main__':
    main()

Measured memory_bytes: 65244
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<map>
#include<set>
#include<vector>
using namespace std;
typedef long long ll;
#define mit map<int,int>::iterator
#define sit set<int>::iterator
#define itrm(g,x) for(mit g=x.begin();g!=x.end();g++)
#define itrs(g,x) for(sit g=x.begin();g!=x.end();g++) 
#define ltype ll
#define rep(i,j,k) for(ltype (i)=(j);(i)<=(k);(i)++)
#define pii pair<int,int>
#define fi first
#define se second
#define mpr make_pair
#define pb push_back
const int inf=0x3f3f3f3f,
mod=1000000007;
const double pi=3.1415926535897932,
eps=1e-6;
ll n,l,p[100005],c[100005],pre[100005],suf[100005],mp[100005],ms[100005],ans,pos,c1;
int main()
{
    scanf("%lld%lld",&n,&l);
    p[n+1]=l;
    rep(i,1,n) scanf("%lld%lld",p+i,c+i);
    ll sum=0;
    rep(i,1,n){
        sum+=c[i]-abs(p[i]-p[i-1]);
        if(pre[i-1]>sum) pre[i]=pre[i-1],mp[i]=mp[i-1];
        else pre[i]=sum,mp[i]=i;
        pre[i]=max(pre[i-1],sum);
        if(sum>c1) ans=sum,pos=i,c1=sum;
    }
    ans=c1;
    sum=0;
    for(int i=n;i>0;i--){
        sum+=c[i]-abs(p[i]-p[i+1]);
        if(suf[i+1]>sum) suf[i]=suf[i+1],ms[i]=ms[i+1];
        else suf[i]=sum,ms[i]=i;
        ans=max(ans,sum);
    }
    sum=0;
    rep(i,1,n){
        ll a=p[mp[i-1]],b=l-p[ms[i]];
        sum=pre[i-1]+suf[i]-min(a,b);
        ans=max(ans,sum);
    }
    //rep(i,1,n) printf("%lld%c",pre[i],i==n?'\n':' ');
    //rep(i,1,n) printf("%lld%c",suf[i],i==n?'\n':' ');
    printf("%lld",ans);
    return 0;
}

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

using namespace std;
#define int int64_t
#define fi first
#define se second
#define endl '\n'


signed main()
{
     srand(time(nullptr));
     ios::sync_with_stdio(false);
     cin.tie(0);
     cout.tie(0);
     int n;
     cin >> n;
     vector<int> a(n * 3);
     for (int i = 0; i < 3 * n; ++i) {
          cin >> a[i];
     }
     sort(a.rbegin(), a.rend());
     int sum = 0;
     for (int i = 1; i < 2 * n; i += 2) {
          sum += a[i];
     }
     cout << sum << endl;
     return 0;
}


Measured memory_bytes: 2560
extern crate core;

use std::io::{self, Read};

#[macro_export]
macro_rules! input {
  ($s:expr=>$($t:tt)*) => {
    let mut lines=$s.split("\n");
    $(
        line_parse!(lines,$t);
    )*
  };
}

macro_rules! line_parse {
  ($lines:expr,($($name:ident:$t:tt)*)) => {
    let mut line=$lines.next().unwrap().split_whitespace();
    $(value_def!(line,$name,$t);)*
  };

  //複数行
  ($lines:expr,{$n:expr;$name:ident:$t:tt}) => {
    values_def!($lines,$n,$name,$t);
  };
}

macro_rules! value_def {
    ($line:expr, $name:ident, $t:tt) => {
        let $name = value!($line, $t);
    };
}

macro_rules! values_def {
    ($lines:expr, $n:expr, $name:ident, $t:tt) => {
        let $name = {
            let mut vec = Vec::new();
            for i in 0..$n {
                let mut next = $lines.next().unwrap().split_whitespace();
                vec.push(value!(next, $t));
            }
            vec
        };
    };
}

macro_rules! value {
  //配列
  ($line:expr,[$t:tt]) => {
    $line.map(|x|{
      let mut iter=::std::iter::once(x);
      value!(iter,$t)
    }).collect::<Vec<_>>()
  };
  //タプル
  ($line:expr,($($t:tt),*)) => {
    ($(value!($line,$t),)*)
  };
  //文字列
  ($line:expr,#) => {
    $line.next().unwrap()
  };
  //インデックス(-1)
  ($line:expr,@) => {
    $line.next().unwrap().parse::<usize>().unwrap()-1
  };
  //単一値
  ($line:expr,$t:ty) => {
    $line.next().unwrap().parse::<$t>().unwrap()
  };
}

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let output = solve(input.trim().to_string());
    println!("{}", output);
}

fn solve(input: String) -> String {
    input!(input=>(a:i64 b:i64 n:i64));
    // floor(a*x/b)-a*floor(x/b)
    /*
    a*x/bの切り捨てが小さい, x/bの切り捨てが多い
    ex1:5 7 4. x=3
    5*3/7=2.14285714286, 3/7=0.42857142857

    x/bはp/aより少し小さい値？

    x<pb/a
    */
    let x = std::cmp::min(n, b - 1);
    (((a * x) / b) - a * (x / b)).to_string()
}

macro_rules! tests {
    ($($name:ident: $input:expr=>$output:expr,)*) => {
        mod tests {
            $(
                #[test]
                fn $name() {
                    assert_eq!($output.trim().to_string(),super::solve($input.trim().to_string()));
                }
            )*
        }
    }
}
tests! {
    test1: "5 7 4\n" => "2\n",
    test2: "11 10 9\n" => "9\n",
}


Measured memory_bytes: 2104
import java.util.Scanner;
class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        
        int n = sc.nextInt();
        int[] num = new int[n];
        for(int i = 0 ; i<n ; i++){
            num[i] = sc.nextInt();
        }
        
        for(int i = 0 ; i < n ; i++){
            if(i != 0){
                System.out.print(" ");
            }
            System.out.print(num[n-i-1]);
        }
        System.out.println();
        
    }
}


Measured memory_bytes: 26300
class Checker:
    d = {
        1: { 2: (3,4,5,6), 3: (5,2,4,6), 4: (2,5,3,6), 5: (4,3,2,6) },
        2: { 1: (4,3,6,5), 3: (1,6,4,5), 4: (6,1,3,5), 6: (3,4,1,5) },
        3: { 1: (2,5,6,4), 2: (6,1,5,4), 5: (1,6,2,4), 6: (5,2,1,4) },
        4: { 1: (5,2,6,3), 2: (1,6,5,3), 5: (6,1,2,3), 6: (2,5,1,3) },
        5: { 1: (3,4,6,2), 3: (6,1,4,2), 4: (1,6,3,2), 6: (4,3,1,2) },
        6: { 2: (4,3,5,1), 3: (2,5,4,1), 4: (5,2,3,1), 5: (3,4,2,1) }
        }

    def __init__(self, s):
        l = s.split()
        self.tbl = dict(zip(l, range(1,7)))
        self.pip = dict(zip(range(1,7), l))

    def __call__(self, s):
        l = s.split()
        if self.tbl[l[1]] in self.d[self.tbl[l[0]]]:
            for i,j in zip(self.d[self.tbl[l[0]]][self.tbl[l[1]]], range(2,6)):
                if self.pip[i] != l[j]:
                    return "No"
            return "Yes"
        else:
            return "No"

c = Checker(input())
print(c(input()))

Measured memory_bytes: 7740
fn main() {
    let s = std::io::stdin();
    let mut sc = Scanner { stdin: s.lock() };

    let n: usize = sc.read();
    let a = sc.read();
    let b = sc.read();
    match solve(n, a, b) {
        Some(ans) => {
            println!("YES");
            for ans in ans.into_iter() {
                print!("{} ", ans);
            }
            println!();
        }
        None => {
            println!("NO");
        }
    }
}

fn solve(n: usize, a: i32, b: i32) -> Option<Vec<i32>> {
    if n == 0 {
        return Some(vec![a]);
    }
    let difference = (0..18).filter(|i| (1 << i) & a != (1 << i) & b).count();
    if difference & 1 == 0 {
        return None;
    }

    let k = (0..).find(|i| (1 << i) & a != (1 << i) & b).unwrap();
    assert!((1 << k) & a != (1 << k) & b);
    let mask = (1 << k) - 1;

    let new_a = ((a >> (k + 1)) << k) + (a & mask);
    let new_b = ((b >> (k + 1)) << k) + (b & mask);
    let x = new_a ^ 1;
    let prefix = if n == 1 {
        Some(vec![new_a])
    } else {
        solve(n - 1, new_a, x)
    };
    let suffix = if n == 1 {
        Some(vec![new_b])
    } else {
        solve(n - 1, x, new_b)
    };
    match (prefix, suffix) {
        (Some(prefix), Some(suffix)) => {
            let mut ans = vec![];
            for p in prefix.into_iter() {
                let prefix = (p >> k) << (k + 1);
                let suffix = p & mask;
                let v = prefix + suffix + ((1 << k) & a);
                ans.push(v);
            }
            for p in suffix.into_iter() {
                let prefix = (p >> k) << (k + 1);
                let suffix = p & mask;
                let v = prefix + suffix + ((1 << k) & b);
                ans.push(v);
            }
            Some(ans)
        }
        _ => None,
    }
}

pub struct Scanner<R> {
    stdin: R,
}

impl<R: std::io::Read> Scanner<R> {
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .stdin
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}


Measured memory_bytes: 5116
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define inf 10e17
#define rep(i,n) for(long long i=0; i<n; i++)
#define repr(i,n,m) for(long long i=m; i<n; i++)
#define mod 1000000007
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<long long>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto&& itr : x) { cerr << (itr) << " "; }

template <class T> inline void chmax(T &ans, T t) { if (t > ans) ans = t;}
template <class T> inline void chmin(T &ans, T t) { if (t < ans) ans = t;}

vector<long long> divisor(long long n) {
  vector<long long> ret;
  for (long long i = 1; i * i <= n; i++) {
    if (n % i == 0) {
      ret.push_back(i);
      if (i * i != n) ret.push_back(n / i);
    }
  }
  sort(ret.begin(), ret.end()); // 昇順に並べる
  return ret;
}

std::vector<ll> set_divisors(ll N)
{
  std::vector<ll> divisors(N + 1);
  for (ll i = 1; i <= N; ++i)//(A)
  {
    for (ll k = 1; k <= N / i; ++k)//(B)
    {
      divisors[i * k] += 1;
    }
  }
  return divisors;
}

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

  ll N;
  cin >> N;

  ll ans = 0;
  auto t = set_divisors(N);

  for (int i = 1; i <= N; ++i) {
    ans += i * t[i];
  }

  cout << ans << endl;
}

Measured memory_bytes: 81316
def main():
    N, K = map(int, input().split())
    S = input()
    if N == 1:
        print(0)
        return

    # print(N, K, S)
    ans = 0

    # RR...
    if S[0] == 'R' and S[1] == 'R':
        ans += 1

    for i in range(1, N - 1):
        cl = S[i - 1]
        cc = S[i + 0]
        cr = S[i + 1]
        if cc == 'L' and cc == cl:
            ans += 1
        elif cc == 'R' and cc == cr:
            ans += 1

    # ...LL
    if S[N - 1] == 'L' and S[N - 2] == 'L':
        ans += 1

    ans += K * 2
    ans = min(ans, N - 1)
    print(ans)

if __name__ == '__main__':
    main()


Measured memory_bytes: 3316
from collections import Counter
N = int(input())
ele_l = [input() for _ in range(N)]
ans = sorted(Counter(ele_l).items(),key=lambda x:-x[1])
maxnum = ans[0][1]
ans = sorted(list(map(lambda x:x[0],list(filter(lambda x:x[1]==maxnum,ans)))))
for a in ans:
    print(a)


Measured memory_bytes: 122960
import java.util.Scanner;

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

	String a = scan.next();
	String b = scan.next();
	String c = scan.next();

	if(a.charAt(a.length()-1) == b.charAt(0) &&
	   b.charAt(b.length()-1) == c.charAt(0)){
	    System.out.println("YES");
	}else{
	    System.out.println("NO");
	}
    }
}


Measured memory_bytes: 21844
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
  int N;
  cin >> N;
  
  int flag = 0;
  for(int i = 0; ;i++){
    if(4*i > N){
      break;
    }//if
    
    for(int j = 0; ; j++){
      int sum = 4*i + 7*j;
      if( sum == N ){
        flag = 1;
        break;
      }else if(sum > N){
        break;
      }
    }//for
    if(flag == 1){
      break;
    }
  }//for
  
  if(flag == 1){
    cout << "Yes" << endl;
  }else{
    cout << "No" << endl;
  }
}

Measured memory_bytes: 3624
#include<stdio.h>
int main(void)
{
	int countN = 0, countS = 0, countW = 0, countE = 0,i=0;
	char S[1010];
	scanf("%s", &S);
	while (S[i] != '\0') {
		if (S[i] == 'N') {
			countN = 1;
		}
		if (S[i] == 'S') {
			countS = 1;
		}
		if (S[i] == 'W') {
			countW = 1;
		}
		if (S[i] == 'E') {
			countE = 1;
		}
		i++;
	}
	if (countN - countS == 0 && countW - countE == 0) {
		printf("Yes");
	}
	else {
		printf("No");
	}
	return 0;
}

Measured memory_bytes: 128
N = int(input())
sara = []
t_s = 0
a_s = 0
for i in range(N):
    A, B = map(int, input().split())
    sara.append([A, B])
sara.sort(key=lambda x:x[0]+x[1], reverse=True)
while True:
    if len(sara) == 0:
        break
    t_s += sara.pop(0)[0]
    if len(sara) == 0:
        break
    a_s += sara.pop(0)[1]
print(t_s - a_s)

Measured memory_bytes: 24408
"use strict"
let fs = require('fs');
let input = fs.readFileSync("/dev/stdin", "utf8").split(/\s/);

const myMin = (a: number, b: number) => a < b ? a : b;

let red = 0, blue = 0;

for(let i=0; i<input[0].length; i++) {
  input[0][i] === '0' ? red++ : blue++;
}

console.log( 2 * myMin(red, blue) );

Measured memory_bytes: 9420
#include <iostream>
#include <cmath>

using namespace std;

typedef long long ll;


int main(){
    int N;
    cin>>N;
    ll A[N];
    ll sum=1;
    bool flag=false;
    bool flag2=false;
    for(int i=0;i!=N;++i){
        cin>>A[i];
        if(A[i]==0){
            flag=true;
        }
    }

    if(flag){
        cout<<0<<endl;
    }else{
        for(int i=0;i!=N;++i){
          //cout<<log10(A[i]*1.0l)<<":"<<log10(sum*1.0l)<<endl;
          if(log10(A[i])+log10(sum)>18){

              flag2=true;
              break;
          }

            sum*=A[i];
            if(sum>1000000000000000000){
                flag2=true;
            }
            
        }
        if(flag2){
            cout<<-1<<endl;
        }else{
            cout<<sum<<endl;
        }
    }
}

Measured memory_bytes: 4328
package main

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

func main() {
	A := nextInt()
	B := nextInt()
	C := nextInt()

	if C >= A && C <= B {
		fmt.Println("Yes")
	} else {
		fmt.Println("No")
	}
}

// Input. ----------

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer([]byte{}, math.MaxInt64)
	sc.Split(bufio.ScanWords)
}

func nextInt() int {
	sc.Scan()
	i, err := strconv.Atoi(sc.Text())
	if err != nil {
		panic(err)
	}

	return i
}

func nextString() string {
	sc.Scan()
	if err := sc.Err(); err != nil {
		panic(err)
	}

	return sc.Text()
}

// ---------- Input.

// Util. ----------

func min(x, y int) int {
	return int(math.Min(float64(x), float64(y)))
}

func max(x, y int) int {
	return int(math.Max(float64(x), float64(y)))
}

// ---------- Util.


Measured memory_bytes: 640
#include<bits/stdc++.h>
#define LL long long
#define M 200020
#define mod 1000000007
using namespace std;
namespace IO{
    const int BS=(1<<22)+5; int Top=0;
    char Buffer[BS],OT[BS],*OS=OT,*HD,*TL,SS[20]; const char *fin=OT+BS-1;
    inline char Getchar(){if(HD==TL){TL=(HD=Buffer)+fread(Buffer,1,BS,stdin);} return (HD==TL)?EOF:*HD++;}
    inline void write(int x){
        if(!x){putchar('0');return;} if(x<0) x=-x,putchar('-');
        while(x) SS[++Top]=x%10,x/=10;
        while(Top) putchar(SS[Top]+'0'),--Top;
    }
    inline int read(){
        int nm=0; char cw=Getchar(); for(;!isdigit(cw);cw=Getchar());
        for(;isdigit(cw);cw=Getchar()) nm=nm*10+(cw-'0'); return nm;
    }
}
using namespace IO;
#define mul(x,y) (LL)(x)*(y)%mod 
#define upd(x,y) x=((x)+(y)>=mod)?(x)+(y)-mod:(x)+(y)
int n,m,fs[M],nt[M<<1],to[M<<1],tmp,ans=1,EG,top,ind[M],node[M];
int S[M],c[M],fa[M],nxt[M],fst[M],tar[M],cur,cnt,sz[M],inv[M],vis[M];
inline void link(int x,int y){
    nt[tmp]=fs[x],fs[x]=tmp,to[tmp++]=y;
    nt[tmp]=fs[y],fs[y]=tmp,to[tmp++]=x;
}
inline void edge(int x,int y){nxt[cur]=fst[x],fst[x]=cur,tar[cur++]=y;}
void init(int x,int last){
    node[++cnt]=x,S[++top]=x,ind[x]=1,S[top+1]=0;
    for(register int i=fs[x];~i;i=nt[i],EG++){
        if(to[i]==last) continue;
        if(!ind[to[i]]){init(to[i],x);continue;}
		if(m) continue;
        while(S[top+1]!=to[i]) vis[c[++m]=S[top--]]=true; c[0]=to[i];
    } top--,ind[x]=2;
}
void build(int x,int last){
    for(register int i=fs[x];~i;i=nt[i]){
        if(vis[to[i]]||to[i]==last) continue;
        fa[to[i]]=x,build(to[i],x);
    }
}
int dfs(int x){
    if(sz[x]) return 1; int res=sz[x]=1;
    for(register int i=fst[x];i!=-1;i=nxt[i]){
        res=mul(res,dfs(tar[i])),sz[x]+=sz[tar[i]];
    } return mul(res,inv[sz[x]]);
}
inline int calc(){
    for(register int i=1;i<=cnt;i++) fst[node[i]]=-1,sz[node[i]]=0; cur=0; int res=1;
    for(register int x=1;x<=cnt;x++) for(register int i=fs[node[x]];i!=-1;i=nt[i]) if(to[i]<fa[node[x]]) edge(node[x],to[i]);
    for(register int x=1;x<=cnt;x++) if(!sz[node[x]]) res=mul(res,dfs(node[x])); return res;
}
inline int solve(int x){
    top=0,init(x,0); if(EG!=(cnt<<1)) puts("0"),exit(0);
    for(register int i=1;i<=m;i++) build(c[i],0); int res=0;
    for(register int i=1;i<=m;i++) fa[c[i-1]]=c[i]; upd(res,calc());
    for(register int i=1;i<=m;i++) fa[c[i]]=c[i-1]; upd(res,calc());
    return res;
}
int main(){
    n=read(),ans=inv[1]=1,memset(fs,-1,sizeof(fs));
    for(int i=2;i<=(n<<1);i++) ans=mul(ans,i),inv[i]=mul(inv[mod%i],mod-(mod/i));
    for(int i=1;i<=(n<<1);i++) link(read()+n,read());
    for(int i=1;i<=(n<<1);i++) if(!ind[i]) cnt=m=EG=0,ans=mul(ans,solve(i));
    printf("%d\n",ans); return 0;
}

Measured memory_bytes: 21248
fun main(args: Array<String>) {
    val S = readLine()!!
    var s = S
    while (true) {
        s = s.dropLast(1)
        if (s.length % 2 == 0) {
            val half = s.length / 2
            if (s.substring(0, half) == s.substring(half, s.length)) {
                println(s.length)
                return
            }
        }
    }
}



Measured memory_bytes: 33728
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;

#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
#define SORT(c) sort((c).begin(), (c).end())

int main()
{
    int n, k, a[200000];
    vector<int> num;
    map<int, int> mp;
    cin >> n >> k;
    num.push_back(100000000);
    REP(i, n)
    {
        cin >> a[i];
        if (mp[a[i]] == 0)
        {
            mp[a[i]] = num.size();
            num.push_back(1);
        }
        else
        {
            num[mp[a[i]]]++;
        }
    }

    SORT(num);

    int ans = 0;
    for (int i = 0; i < (int)num.size() - k - 1; i++)
    {
        ans += num[i];
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 11124
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <string>

using namespace std;

int n,k,r,s,p;

int getScore(const string& str){
    if(str == "r") return p;
    else if(str == "s") return r;
    else return s;
}

void solve() {
    cin >> n >> k >> r >> s >> p;
    string t;
    cin >> t;
    vector<string> datas(n);
    int64_t score = 0;
    for(int i = 0; i < n; i++){
        datas[i] = t.substr(i, 1);
    }

    for(int i = 0; i < k; i++){
        bool flag = false;
        score += getScore(datas[i]);
        for(int j = i+k; j < n; j+=k){
            if(datas[j] == datas[j-k]){
                if(flag){
                    flag = false;
                    score += getScore(datas[j]);
                } else {
                    flag = true;
                }
            } else {
                flag = false;
                score += getScore(datas[j]);
            }
        }
    }

    cout << score;
}

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

Measured memory_bytes: 5760
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll mod = 1e9 + 7;
const int inf = (1 << 30) - 1;
const ll infll = (1LL << 61) - 1;

int N;
ll ans = 1;

int main()
{
    cin >> N;
    vector<ll> T(N), A(N), com(N);
    for (int i = 0; i < N; i++)
        cin >> T[i];
    for (int i = 0; i < N; i++)
        cin >> A[i];

    bool flag = 1;

    for (int i = 0; i < N; i++)
    {
        if (i == 0 && T[i] > A[i])
            flag = false;
        if (i != 0 && T[i] != T[i - 1] && T[i] > A[i])
            flag = false;

        if (i == 0 && A[N - i - 1] > T[N - i - 1])
            flag = false;
        if (i != 0 && A[N - i - 1] != A[N - i] && A[N - i - 1] > T[N - i - 1])
            flag = false;
    }

    if (flag == false)
    {
        puts("0");
        return 0;
    }

    com[0] = 1LL, com[N - 1] = 1LL;
    for (int i = 1; i + 1 < N; i++)
    {
        if (T[i - 1] != T[i] || A[i + 1] != A[i])
            com[i] = 1LL;
        else
            com[i] = min(T[i], A[i]);

        ans *= com[i];
        ans %= mod;
    }
    cout << ans % mod << endl;
}


Measured memory_bytes: 2560
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>

using namespace std;

struct UnionFind {
	vector<int> data;
	UnionFind(int size) : data(size, -1) { }
	bool unionSet(int x, int y) {
		x = root(x); y = root(y);
		if (x != y) {
			if (data[y] < data[x]) swap(x, y);
			data[x] += data[y]; data[y] = x;
		}
		return x != y;
	}
	bool findSet(int x, int y) {
		return root(x) == root(y);
	}
	int root(int x) {
		return data[x] < 0 ? x : data[x] = root(data[x]);
	}
	int size(int x) {
		return -data[root(x)];
	}
};

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

	vector<int> p(N);
	for (auto &x : p) {
		cin >> x;
		--x;
	}
	for (int i = 0; i < M; ++i) {
		int x, y;
		cin >> x >> y;
		--x;
		--y;
		u.unionSet(x, y);
	}

	int ans = 0;
	for (int i = 0; i < N; ++i) {
		if (u.findSet(i, p[i])) {
			++ans;
		}
	}
	cout << ans << endl;
}


Measured memory_bytes: 1024
#include <stdio.h>
#include <iostream>
using namespace std;

class Node {
private:
	int id;
	Node *parent;
	Node *child_l;
	Node *child_r;
public:
	Node(int id){ this->id = id; parent = NULL; child_l = NULL; child_r = NULL;}
	void setChildl(Node *nl);
	void setChildr(Node *nr);
	void setParent(Node *np){ parent = np; }
	int getId(){ return id; }
	Node *getParent(){ return parent; }
	Node *getChildl(){ return child_l; }
	Node *getChildr(){ return child_r; }
};

void Node::setChildl(Node *nl)
{
	child_l = nl;
	if (child_l != NULL) child_l->setParent(this);
}

void Node::setChildr(Node *nr)
{
	child_r = nr;
	if (child_r != NULL) child_r->setParent(this);
}

class BinaryTree {
private:
	Node *root;
	void walkPreorder(Node *node);
	void walkInorder(Node *node);
public:
	BinaryTree(){ root = NULL; }
	void insert(int id);
	void walkPreorder();
	void walkInorder();
};

void BinaryTree::insert(int id)
{
	if (root == NULL) {
		root = new Node(id);
		return;
	}

	Node *node = root;
	while (1) {
		if (id < node->getId()) {
			if (node->getChildl() == NULL) {
				node->setChildl(new Node(id));
				break;
			}
			else {
				node = node->getChildl();
			}
		}
		else if (id > node->getId()) {
			if (node->getChildr() == NULL) {
				node->setChildr(new Node(id));
				break;
			}
			else {
				node = node->getChildr();
			}
		}
	}
}

void BinaryTree::walkPreorder()
{
	walkPreorder(root);
	cout << endl;
}

void BinaryTree::walkPreorder(Node *node)
{
	if (node == NULL) return;
	cout << " " << node->getId();
	walkPreorder(node->getChildl());
	walkPreorder(node->getChildr());
}

void BinaryTree::walkInorder()
{
	walkInorder(root);
	cout << endl;
}

void BinaryTree::walkInorder(Node *node)
{
	if (node == NULL) return;
	walkInorder(node->getChildl());
	cout << " " << node->getId();
	walkInorder(node->getChildr());
}

int main(void)
{
	BinaryTree bt;

	int m;
	cin >> m;
	for (int i = 0; i < m; i++) {
		char command[7] = "\0";
		cin >> command;
		if (command[0] == 'i') {			
			int id;
			cin >> id;
			bt.insert(id);
		}
		else {
			bt.walkInorder();
			bt.walkPreorder();
		}
	}
		
	return 0;
}

Measured memory_bytes: 26512
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <stack>
#include <functional>
#include <queue>
#include <tuple>
#include <cstring>

using namespace std;

#define rep(i,n) for(int i = 0;i < n;i++)
#define each(i,n) for(auto i : n)
#define all(n) n.begin(),n.end()
#define clr(n) memset(n,0,sizeof(n))
#define mclr(n) memset(n,-1,sizeof(n))

int main() {
	int n, a, b, m;
	cin >> n >> a >> b >> m;

	typedef pair<int, int> P;
	map<int, P> ap, bp;
	rep(y, n)rep(x, n) {
		int t;
		cin >> t;
		ap[t] = P(y, x);
	}
	rep(y, n)rep(x, n) {
		int t;
		cin >> t;
		bp[t] = P(y, x);
	}
	map<int, int> ax, ay, axy, ayx;
	map<int, int> bx, by, bxy, byx;

	bool aw = 0, bw = 0;
	int ac = 0, bc = 0;
	rep(i, m) {
		int t;
		cin >> t;
		if (n == 1) {
			ac += ap.count(t);
			bc += bp.count(t);
		}
		else {
			if (ap.count(t)) {
				int y = ap[t].first, x = ap[t].second;
				ax[x]++; ay[y]++;
				ayx[y - x]++; axy[x + y]++;
				if (ax[x] >= n) {
					ac++;
				}
				if (ay[y] >= n) {
					ac++;
				}
				if (ayx[y - x] >= n) {
					ac++;
				}
				if (axy[x + y] >= n) {
					ac++;
				}
			}
			if (bp.count(t)) {
				int y = bp[t].first, x = bp[t].second;
				bx[x]++; by[y]++;
				byx[y - x]++; bxy[x + y]++;
				if (bx[x] >= n) {
					bc++;
				}
				if (by[y] >= n) {
					bc++;
				}
				if (byx[y - x] >= n) {
					bc++;
				}
				if (bxy[x + y] >= n) {
					bc++;
				}
			}
		}
		if (ac >= a)aw = 1;
		if (bc >= b)bw = 1;
		if (aw && bw) {
			cout << "DRAW" << endl;
			return 0;
		}
		if (aw) {
			cout << "USAGI" << endl;
			return 0;
		}
		if (bw) {
			cout << "NEKO" << endl;
			return 0;
		}
	}
	cout << "DRAW" << endl;
	return 0;
}

Measured memory_bytes: 21212
import itertools

N = int(input())
p = list(map(int,input().split()))
q = list(map(int,input().split()))
r = list(range(1,N+1))


a_temp = 0
b_temp = 0

for r_temp in itertools.permutations(r):
	a_temp += 1
	b_temp += 1
	if list(r_temp) == p:
		a = a_temp
	if list(r_temp) == q:
		b = b_temp
print(abs(a-b))


Measured memory_bytes: 3188
import java.util.*;
class Main
{
    public static void main (String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++){
            a[i] = sc.nextInt();
        }
        int ans = a[0];
        for(int i = 1; i < n; i++){
            ans = gcd(ans, a[i]);
        }
        System.out.println(ans);
    }
    static int gcd (int a, int b){
        if(a == 0) return b;
        if(a > b) return gcd(b, a);
        return gcd(a, b % a);
    }
}
 

Measured memory_bytes: 50232
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 main() {
    input!(
    r: f64,
    );
    let pi = std::f64::consts::PI;
    let ans = 2.0 * r * pi;
    println!("{}", ans);
}


Measured memory_bytes: 2232
#include <bits/stdc++.h>
using namespace std;
int main() {
   int a, b, c, k;
   cin >> a >> b >> c >> k;
   if(k <= a) {
       cout << k << endl;
   } else if(k <= a+b) {
       cout << a << endl;
   } else {
       cout << a -(k-a-b) << endl;
   }
   return 0;
}


Measured memory_bytes: 3608
#include<bits/stdc++.h>
using namespace std;
 
 
int main(){

    int N,K;
    cin >> N >> K;
    vector<int> p(N);
    for(int i = 0; i < N; i++){
        cin >> p[i];
    }

    sort(p.begin(),p.end());

    int ans = 0;

    for(int i = 0; i < K; i++){
        ans += p[i];
    }

    cout << ans << endl;

}

Measured memory_bytes: 3624