akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <cstdio>
#include <ios>
#include <vector>
using namespace std;
using ll = long long;

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

int main(){
    ios::sync_with_stdio(false);
    const ll mod = 1000000007;
    //dp[i]: i段目にたどり着く組み合わせの総数
    int N, M; cin >> N >> M;
    vector<ll> a(M,0);
    vector<ll> dp(N+3,0);
    vector<bool> broken(N+1,false);
    for(int i = 0; i < M; i++) {
        cin >> a[i];
        broken[a[i]] = true;
    }
    dp[0] = 1;
    for(int i = 0; i < N; i++) {
        dp[i] %= mod;
        if(broken[i+1] == false) dp[i+1] += dp[i];
        if(broken[i+2] == false) dp[i+2] += dp[i];
    }
    cout << dp[N]%mod << "\n";
}

Measured memory_bytes: 1792
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
ll chk(ll n,ll a,ll b)
{
    ll s=a*n;
    ll s1=0;
    while(n)
    {
        s1++;
        n/=10;
    }
    s+=b*s1;
    return s;
}
int main()
{
    ll n;
    cin>>n;
    string s;
    cin>>s;
    ll flg=0;
    if(n%2)
    flg=1;
    else
{
    for(ll i=0;i<n/2;i++)
    {
        if(s[i]!=s[i+n/2])
        flg=1;
    }
}
if(flg)
cout<<"No";
else
cout<<"Yes";
}

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

using namespace std;

int main()
{
	bool flag = true;
	string S;
	cin >> S;

	int i = S.size();

	if (S.size() < 5)
	{
		cout << "NO" << endl;
		flag = false;
	}
	else
	{
		int i = S.size();

		while (i > 0)
		{
			if (i >= 5 && (S.substr(i - 5, 5) == "dream" || S.substr(i - 5, 5) == "erase"))
			{
				i -= 5;
			}
			else if (i >= 6 && S.substr(i - 6, 6) == "eraser")
			{
				i -= 6;
			}
			else if (i >= 7 && S.substr(i - 7, 7) == "dreamer")
			{
				i -= 7;
			}
			else
			{
				cout << "NO" << endl;
				flag = false;
				break;
			}
		}
	}

	if (flag)
		cout << "YES" << endl;

	return 0;
}

Measured memory_bytes: 512
a, b = map(int, input().split())

def gcd(a, b):
    while b != 0:
        a, b = b, a % b
    return a


def prime_factorization(n):
    res = []
    for i in range(2, int(pow(n, 0.5)) + 1):
        if n % i == 0:
            ex = 0
            while n % i == 0:
                ex += 1
                n //= i
            res.append([i, ex])
    if n != 1:
        res.append([n, 1])
    prime = []
    for p in res:
        for _ in range(p[1]):
            prime.append(p[0])
    return prime

n = gcd(a,b)
prime = set(prime_factorization(n))
print(len(prime) + 1)

Measured memory_bytes: 3192
A = [list(map(int, input().split())) for _ in range(3)]
N = int(input())
b = [int(input()) for _ in range(N)]

for num in b:
    for i in range(3):
        for j in range(3):
            if A[i][j] == num:
                A[i][j] = 0

ans = "No"
for i in range(3):
    if sum(A[i]) == 0:
        ans = "Yes"

for i in range(3):
    if A[0][i] + A[1][i] + A[2][i] == 0:
        ans = "Yes"

if A[0][0] + A[1][1] + A[2][2] == 0:
    ans = "Yes"
if A[0][2] + A[1][1] + A[2][0] == 0:
    ans = "Yes"

print(ans)

Measured memory_bytes: 3064
#include<stdio.h>
#include<string>
#include<utility>
#include<iostream>
#include<queue>
#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
#include<stack>
#include<bitset>

using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0;i<(int)(n);i++)

int main(){
    int r;
    scanf("%d",&r);
    printf("%d\n",r*r);
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	cin>>n;
	pair<pair<string,int>,int> pr[n];
	for(int i=0;i<n;i++){
		string s;
		int p;
		cin>>s>>p;
		pr[i].first.first=s;
		pr[i].first.second=-p;
		pr[i].second=i+1;
	}
	sort(pr,pr+n);
	for(int i=0;i<n;i++)
		cout<<pr[i].second<<endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define ll long long
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) // rep(i, 1, 5) --> {1,2,3,4} // rep(i, 5, 1) --> {4,3,2,1} // rep(it, end(v), begin(v)) --> *it

using namespace std;

int main()
{
    int w, h, n;
    cin >> w >> h >> n;
    int xmin = w, xmax = 0, ymin = h, ymax = 0;
    rep(i, 0, n)
    {
        int x, y, a;
        cin >> x >> y >> a;
        if (a == 1)
            xmax = max(xmax, x);
        if (a == 2)
            xmin = min(xmin, x);
        if (a == 3)
            ymax = max(ymax, y);
        if (a == 4)
            ymin = min(ymin, y);
    }
    cout << max(0, xmin-xmax) * max(0, ymin-ymax);
    return 0;
}

Measured memory_bytes: 256
x = int(input())
a = [pow(i, 5) for i in range(-121, 122)]
flag = 0
for i in range(len(a)):
    for j in range(i+1, len(a)):
        if a[i] - a[j] == x:
            print(i-121, j-121)
            flag = 1
            break
        elif a[j] - a[i] == x:
            print(j-121, i-121)
            flag = 1
            break
    if flag == 1:
        break

Measured memory_bytes: 9236
#include <iostream>

int main(int argc, const char * argv[]) {
    
    int a, b ;
    
    std::cin >> a >> b ;
    
    int j = a-b ;
    
    if (j>0) {
        std::cout << "a > b" << std::endl ;
    } else if (j<0) {
        std::cout << "a < b" << std::endl ;
    } else {
        std::cout << "a == b" << std::endl ;
    }
    
    
    
    return 0;
}


Measured memory_bytes: 3080
M, K = map(int, input().split())

if K >= 2 ** M:
    print(-1)
elif (M, K) == (1, 0):
    print(*(0, 0, 1, 1))
elif (M, K) == (1, 1):
    print(-1)
else:
    # 3, 5 -> [7 6 4 3 2 1 0 5 0 1 2 3 4 6 7 5]
    ans = [0] * (2 ** (M + 1))
    ans[2 ** M - 1] = ans[-1] = K

    num = 0
    for i in range(2 ** M - 1):
        if num == K:
            num += 1
        ans[2 ** M - i - 2] = ans[2 ** M + i] = num
        num += 1
    print(*ans)


Measured memory_bytes: 17460
#include <algorithm> // std::sort(begin,end), std::min, std::max
#include <iostream>
#include <queue>
#include <string>
#include <unordered_map>
#include <utility> // std::swap
#include <vector>

using namespace std;
using ll = long long;
using pii = pair<int, int>;

template <typename T> // 0<1<2<3<4
using pq_asc = priority_queue<T, vector<T>, greater<T>>;
template <typename T> // 0>1>2>3>4
using pq_dsc = priority_queue<T>;

int main(int argc, char const *argv[]) {
  ll n;
  string s;
  cin >> n >> s;
  int ret = 0;
  char prev_c = ' ';
  for (char c : s) {
    if (prev_c != c) {
      ret++;
    }
    prev_c = c;
  }

  cout << ret << endl;

  return 0;
}


Measured memory_bytes: 512
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define rep(i,m,n) for(int i=m;i<n;i++)
ll mod=1e9+7;

int main(){
  int n,m;
  cin>>n>>m;
  int c[m];
  rep(i,0,m) c[i]=0;
  rep(i,0,n){
    int k;
    cin>>k;
    rep(j,0,k){
      int a;
      cin>>a;
      c[a-1]++;
    }
  }
  int d=0;
  rep(i,0,m){
    if(c[i]==n) d++;
  }
  cout<<d<<endl;
}

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

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

typedef long long ll;

using namespace std;

string dictionaryComp(string s1, string s2)
{
    string ret;
    int len = min(s1.size(), s2.size());
    bool isSame = true;
    for (int i = 0; i < len; ++i)
    {
        if (s1[i] == s2[i])
        {
            continue;
        }
        else if (s1[i] < s2[i])
        {
            ret = s1;
            isSame = false;
            break;
        }
        else
        {
            ret = s2;
            isSame = false;
            break;
        }
    }

    if (isSame)
    {
        ret = s1.size() <= s2.size() ? s1 : s2;
    }
    return ret;
}

int main()
{
    string Sd, T;
    cin >> Sd >> T;
    int sLen = Sd.size();
    int tLen = T.size();
    vector<int> stVec;
    REP(i, sLen)
    {
        bool isInclude = true;
        REP(j, tLen)
        {
            if (!(Sd[i + j] == T[j] || Sd[i + j] == '?'))
            {
                isInclude = false;
            }
        }
        if (isInclude)
        {
            stVec.push_back(i);
        }
    }

    string ans;
    if (stVec.size() == 0)
    {
        ans = "UNRESTORABLE";
    }
    else
    {
        ans = string(50, 'z');
        REP(i, stVec.size())
        {
            string S;
            S = Sd;
            int st = stVec[i];
            REP(j, tLen)
            {
                if (S[st + j] == '?')
                {
                    S[st + j] = T[j];
                }
            }
            REP(j, sLen)
            {
                if (S[j] == '?')
                {
                    S[j] = 'a';
                }
            }
            ans = dictionaryComp(ans, S);
        }
    }
    
    cout << ans << endl;
}


Measured memory_bytes: 256
#include "bits/stdc++.h"
using namespace std;
#ifdef _DEBUG
#define dlog(str) cout << "====" << str << endl;
#else
#define dlog(str)
#endif
#define INF 999999999
#define MOD 1000000007
#define REP(i, n) for(int i = 0, i##_l = (n); i < i##_l; i++)
#define FOR(i, s, e) for(int i = s, i##_l = (e); i < i##_l; i++)
#define LLI long long int
#define _min(a,b) ((a<b)?a:b)
#define _max(a,b) ((a<b)?b:a)
#define chmax(a, b) a = _max(a, b)
#define chmin(a, b) a = _min(a, b)
#define bit(a, shift) ((a>>shift)&1))
#define pm(a) ((a)?1:-1)
#define SORT(v) sort(v.begin(),v.end())
#define RSORT(v) sort((v).rbegin(), (v).rend())
// int 2.14E±9    lli 9.2E±18    double 1.7E±380


int main()
{
    cout << fixed << setprecision(10);
    int n, k;
    cin >> n >> k;

    vector<int> a(n);
    REP(i, n)
    {
        cin>>a[i];
    }
    RSORT(a);

    LLI l = 1, r = 1e9;

    while (l < r)
    {
        LLI m = (l + r) / 2;
        int c = 0;
        REP(i, n)
        {
            c += (a[i] - 1) / m;
        }

        if (c <= k)
        {
            r = m;
        }
        else
        {
            l = m+1;
        }
    }
    cout << l  << endl;



    return 0;
}

Measured memory_bytes: 4048
#include<iostream>
#include<cstring>
#include<cstdio>
#include<vector>
#include<algorithm>

using namespace std;

#define LL long long
#define fgx cerr<<"--------------"<<endl;
#define dgx cerr<<"=============="<<endl;

inline int read(){
	int x=0,f=1;char c=getchar();
	for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;
	for(;isdigit(c);c=getchar()) x=x*10+c-'0';
	return x*f;
}
const int MAXN = 1000010;
const int INF = 2147483600;

int N,M,Q,Mod; int fa[MAXN+1]; bool f[2][MAXN+1];
int a[MAXN+1],b[MAXN+1],c[MAXN+1];
inline int gcd(int a,int b){ if(!b) return a; return gcd(b,a%b); }
inline int Id(int x,int y,int z){ return x*6+y*2+z; }
inline int find(int x){ return (fa[x]==x?fa[x]:(fa[x]=find(fa[x]))); }
inline void link(int u,int v){ if(find(u)==find(v)) return ;fa[find(v)]=find(u); }

int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	N=read(),M=read(),Q=read(),Mod=read(); int g=0;
	for(int i=1;i<=M;i++) {
		a[i]=read(),b[i]=read(),c[i]=read();
		g=gcd(g,abs(c[i]-c[1]));
	} 
	if(!g) g=Mod; Mod=gcd(Mod,3*g); LL z=c[1]%g;
	for(int i=0;i<6*N;i++) fa[i]=i;
	for(int i=1;i<=M;i++){
		int u=a[i]-1,v=b[i]-1,w=((c[i]-z)/g)%3;
		for(int x=0;x<3;x++){
			link(Id(u,x,0),Id(v,(x*2+w)%3,1));
			link(Id(u,x,1),Id(v,(x*2+w)%3,0));
			link(Id(v,x,0),Id(u,(x*2+w)%3,1));
			link(Id(v,x,1),Id(u,(x*2+w)%3,0));
		}
	} 
	for(int i=0,nw=z;i<(Mod<<1);nw=(nw<<1)%Mod,i++) f[i&1][nw]=1;
	while(Q--){
		bool can=0;
		int u=read(),v=read(),r=read(); --u; --v;
		for(int j=0;j<2;j++)
			for(int k=0;k<3;k++){
				if(find(Id(v,0,0))==find(Id(u,k,j))){
					can|=f[j][(r+z+(3-k)*g)%Mod];
				}
			}
		if(can) puts("YES"); else puts("NO");
	}
	return 0;
}




Measured memory_bytes: 7192
def main():
    n, x = map(int, input().split())

    if x == 1 or x == 2 * n - 1:
        print("No")
    elif x == 2:
        print("Yes")
        lst = [i for i in range(1, x-1)] + [i for i in range(x+3, 2*n)]
        for i in range(n-2):
            print(lst[i])
        print(x+1)
        print(x)
        print(x-1)
        if n >= 3:
            print(x+2)
        for i in range(n+2, 2*n-1):
            print(lst[i-4])
    else:
        print("Yes")
        lst = [i for i in range(1, x-2)] + [i for i in range(x+2, 2*n)]
        for i in range(n-2):
            print(lst[i])
        print(x-1)
        print(x)
        print(x+1)
        print(x-2)
        for i in range(n+2, 2*n-1):
            print(lst[i-4])


if __name__ == '__main__':
    main()


Measured memory_bytes: 12596
def porland(M):
    for i in range(len(M)):
        if len(M)==1:
            print(' '.join(map(str, M)))
        elif M[i]=='+':
            M[i] = int(M[i-2])+int(M[i-1])
            M.pop(i-2)
            M.pop(i-2)
            porland(M)
            break
        elif M[i]=='-':
            M[i] = int(M[i-2])-int(M[i-1])
            M.pop(i-2)
            M.pop(i-2)
            porland(M)
            break
        elif M[i]=='*':
            M[i] = int(M[i-2])*int(M[i-1])
            M.pop(i-2)
            M.pop(i-2)
            porland(M)
            break
        else :
            M[i] = int(M[i])

if __name__ == '__main__':
    N = list(input().split())
    porland(N)


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

typedef long long ll;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr)
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second

int n,m;
int k[200], s[200][20], h[200][20];

double dp[201][201];
double dfs(int now, int r)
{
    if(now==n) return 0;
    if(dp[now][r]>=0) return dp[now][r];

    double ret=0;

    rep(i,r+1)
    {
        double add=0;
        int tr=i;
        rep(j,k[now])
        {
            int d=s[now][j]*h[now][j];
            if(tr-d<0)
            {
                add+=(double)tr/s[now][j];
                break;
            }

            tr-=d;
            add+=h[now][j];
        }
        ret=max(ret,dfs(now+1,r-i)+add);
    }

    return dp[now][r]=ret;
}

int main()
{
    scanf(" %d %d", &n, &m);
    rep(i,n)
    {
        scanf(" %d", &k[i]);
        rep(j,k[i]) scanf(" %d %d", &s[i][j], &h[i][j]);
    }

    fill(dp[0],dp[201],-1.0);
    printf("%.10f\n", dfs(0,m));
    return 0;
}

Measured memory_bytes: 3584
#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
#include<numeric>
#include<algorithm>
#include<complex>
#include<queue>
#include<stdlib.h>
#include<map>
#include<cmath>

#include<stdio.h>
#include<stdlib.h>

#define ll long long

using namespace std;

int main(){
    vector<int> vec(3,0);
    cin >> vec[0] >> vec[1] >> vec[2];
    sort(vec.begin(),vec.end());
    cout << vec[2]-vec[0] << endl;
    return 0;
}



Measured memory_bytes: 256
from collections import *
h,w=map(int,input().split())
a=[input() for _ in range(h)]
b=[[h*w]*w for _ in range(h)]
b[0][0]=1
d=deque([[0,0]])
while d:
    y,x=d.popleft()
    for i,j in([1,0],[-1,0],[0,1],[0,-1]):
        t,u=y+i,x+j
        if h>t>=0<=u<w:
            if a[t][u]=="." and b[t][u]>b[y][x]+1:
                d.append([t,u])
                b[t][u]=b[y][x]+1
print(max(-1,sum([i.count(".") for i in a])-b[-1][-1]))

Measured memory_bytes: 3436
#include <stdio.h>
#define max(x,y) ((x)>(y)?(x):(y))
#define min(x,y) ((x)<(y)?(x):(y))
#define FOR(i,m,n) for(i=m;i<n;i++)

int main(void)
{
	int a,b,i,c=0;
	scanf("%d %d",&a,&b);
	for(i=0;i<2;i++){
		if(a<b){
			c=c+b;
			b--;
		}else{
			c=c+a;
			a--;
		}
	}
	printf("%d",c);
	return 0;
}

Measured memory_bytes: 128
from time import time 
N = int(input())
S = str(input())
t0 = time()
x, y, z = 0,0,0
for i in range(N):
    if S[i] == "R":
        x += 1
    elif S[i] == "G":
        y += 1
    elif S[i] == "B":
        z += 1
    else:
        print("ERROR")

no = 0
for s in range(N-2):
    d = 1
    while(s+2*d < N):
#         if len(set([S[s],S[s+d],S[s+2*d]])) == 3:
        a = S[s]
        b = S[s+d]
        c = S[s+2*d]
        if a != b and b != c and c != a:
            no += 1
        d += 1

print(x*y*z-no)
# print(time() - t0)


Measured memory_bytes: 9116
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**6)
INF = 10 ** 9 + 1  # sys.maxsize # float("inf")
MOD = 998244353


def debug(*x):
    print(*x, file=sys.stderr)


def solve(N, K, SS):
    count = [0] * (N + 10)
    count[0] = 1
    accum = [0] * (N + 10)
    accum[0] = 1

    for pos in range(1, N):
        ret = 0
        for left, right in SS:
            start = pos - right - 1
            end = pos - left
            ret += (accum[end] - accum[start])
            ret %= MOD
        count[pos] = ret
        accum[pos] = accum[pos - 1] + ret

    ret = count[N - 1]
    return ret % MOD


def main():
    # parse input
    N, K = map(int, input().split())
    SS = []
    for i in range(K):
        SS.append(tuple(map(int, input().split())))
    print(solve(N, K, SS))


# tests
T1 = """
5 2
1 1
3 4
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
4
"""

T2 = """
5 2
3 3
5 5
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
0
"""

T3 = """
5 1
1 2
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
5
"""

T4 = """
60 3
5 8
1 3
10 15
"""
TEST_T4 = """
>>> as_input(T4)
>>> main()
221823067
"""

T5 = """
10 1
1 2
"""
TEST_T5 = """
>>> as_input(T5)
>>> main()
55
"""


def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            doctest.run_docstring_examples(g[k], g, name=k)


def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")


input = sys.stdin.buffer.readline
read = sys.stdin.buffer.read

if sys.argv[-1] == "-t":
    print("testing")
    _test()
    sys.exit()

main()


Measured memory_bytes: 76744
#include <bits/stdc++.h>
#define rep(i, s, n) for (int i = s; i < n; i++)
#define rp(i,n) for (int i=0;i<n;i++)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define all_acc(x) (x).begin(), (x).end(), 0LL
#define int long long
#define absSort(v) sort(a.begin(), a.end(), [](int i, int j) -> bool { return abs(i) < abs(j); });
using namespace std;
using P = pair<int, int>;
using Graph = vector<vector<int>>;
using ll = long long;
double pi=3.14159265359;

//出力するよ
void output_tate(vector<int> s){
    int n = s.size();
    for (int i = 0; i < n; i++){
        //if (i != 0)
        //    cout << " ";
        cout << s[i]<<endl;
    }
    //cout << endl;
}

void output_yoko(vector<int> s){
    int n = s.size();
    for (int i = 0; i < n; i++){
        if (i != 0)
            cout << " ";
        cout << s[i];//<<endl;
    }
    cout << endl;
}

int MOD = pow(10, 9) + 7;

int kaijou(int n){
    if(n==0) return 1;
    else{
        return ((n%MOD)*(kaijou(n-1)%MOD))%MOD;
    }
}

bool ispow(int n){
    int rn=sqrt(n);
    if(rn*rn==n) return true;
    else return false;
}

signed main() {
    int n,h; cin>>n>>h;
    int ans=0;

    vector<pair<int,int>> ab(n),ba(n);
    vector<int> b(n);

    for(int i=0;i<n;i++){
        int ai,bi;cin>>ai>>bi;
        ab[i]=make_pair(ai,bi);
        b[i]=bi;
    }

    sort(all(ab));
    sort(all(b));

    //cout<<1<<endl;

    int a_max=ab.at(n-1).first;
    int throw_index=distance(b.begin(),upper_bound(all(b),a_max));//投げたほうが効率が良いポイント

    //cout<<throw_index<<endl;

    for(int i=n-1;i>=throw_index;i--){
        h-=b.at(i);
        ans++;
        if(h<=0){
            cout<<ans<<endl;
            return 0;
        }
    }

    int a_cnt=h/a_max;
    if((h%a_max)!=0) a_cnt++;

    ans+=a_cnt;

    cout<<ans<<endl;
}


Measured memory_bytes: 7112
#include<bits/stdc++.h>
using namespace std;
const long double p=3.14159265358979;
int main(){
  long double a,b,x;
  cin>>a>>b>>x;
  if(a*a*b/2<x)
    cout<<fixed<<setprecision(16)<<atan((a*a*b-x)*2/a/a/a)*180/p<<endl;
  else
    cout<<fixed<<setprecision(16)<<90-atan(x*2/a/b/b)*180/p<<endl;
}

Measured memory_bytes: 3720
#include <cmath>
#include <cstdio>
#include <vector>
#include <map>
#include <queue>
#include <list>
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < (n); ++i)
using P = pair<int, int>;

vector< int64_t > divisor(int64_t n) {
  vector< int64_t > ret;
  for(int64_t i = 1; i * i <= n; i++) {
    if(n % i == 0) {
      ret.push_back(i);
      if(i * i != n) ret.push_back(n / i);
    }
  }
  sort(begin(ret), end(ret));
  return (ret);
}

ll func(ll a, ll b) {
  return pow(a, 4) + pow(a, 3) * b + pow(a, 2) * pow(b, 2) + a * pow(b, 3) + pow(b, 4);
}

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

  ll x;
  cin >> x;

  for (const auto d : divisor(x)) {
    ll start = - d / 2;
    const ll upper = 200;
    const ll lower = -upper;

    ll left = start;
    ll right = upper;

    while(right - left > 1) {
      // cout << d << ", " << left << ", " << right << endl;
      ll m = (left + right) / 2;
      if (func(m + d, m) * d > x) left = m;
      else right = m;
    }
    if (func(left + d, left) * d == x) {
        cout << left + d << " " << left << endl;
        return 0;
    }

    left = lower;
    right = start;

    while(right - left > 1) {
      // cout << d << ", " << left << ", " << right << endl;
      ll m = (left + right) / 2;
      if (func(m + d, m) * d < x) right = m;
      else left = m;
    }
    if (func(left + d, left) * d == x) {
        cout << left + d << " " << left << endl;
        return 0;
    }
  }


}

Measured memory_bytes: 4088
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <limits>
#include <map>
#include <stack>
#include <map>
#include <unordered_map>
#define REP(i,n) for(long (i)=0;(i)<(n);(i)++)
#define REPI(i,a,b) for(long (i)=(a);(i)<(b);(i)++)
#define INF numeric_limits<double>::infinity()
constexpr long MOD = 1e9 + 7;
using namespace std;
using P = pair<long, long>;
using VI = vector<long>;

int d[101];

int main() {
    int n, a;
    cin >> n;
    REP(i,n) {
        cin >> a;
        d[a]++;
    }
    int cnt = 0;
    REP(i,101) {
        if (d[i]) cnt++;
    }
    cout << cnt << endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
int main(){
   string s;
  cin>>s;
  int l = s.size();
  if(s[l-1] == 's'){
    cout<<s;
         cout<<"es"<<endl;
         
  }
  else{ cout<<s;
        cout<<"s"<<endl;}
  
}

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

int main(void) {
  int i, n, min = 1e9, max = 0, minn = 0, ans = 0, maxn = 0, t;
  scanf("%d%d", &n, &t);
  int a[n];
  for(i = 0; i < n; ++i) {
    scanf("%d", &a[i]);
    if(a[i] < min) min = a[i];
    if(a[i] - min > max) max = a[i] - min;
  }
  min = 1e9;
  for(i = 0; i < n; ++i) {
    if(a[i] < min) min = a[i], ans += minn < maxn ? minn : maxn, minn = 1, maxn = 0;
    else if(a[i] == min) minn++;
    if(a[i] - min == max) maxn++;
  }
  ans += minn < maxn ? minn : maxn;
  printf("%d", ans);
  return 0;
}

Measured memory_bytes: 512
list=[]
while True:
    try:
        x=int(input())
    except:
        break
    list.append(x)

tmp=1
ans=[]
for i in range(100):
    num=0
    for l in range(len(list)):
        if i==list[l]:
            num+=1
    if num>tmp:
        tmp=num
        ans=[i]
    elif num==tmp:
        ans.append(i)
for n in range(len(ans)):
    print(ans[n])



Measured memory_bytes: 5596
#include<bits/stdc++.h>
#define N 1000000
#define ll long long int
#define pr pair<ll,ll>
#define ff first
#define ss second
#define pub push_back
#define pob pop_back
#define f(i,a,b) for(ll i=a;i<=b;i++)
#define r(i,a,b) for(ll i=a;i>=b;i--)
#define ms(a,b) memset(a,b,sizeof(a));
using  namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    ll tt = 1;  
    //cin>>tt;
    while(tt--){
        ll x; cin>>x;
        ll gtprime;
        bool prime[N];
        ms(prime,true);
        prime[0] = prime[1] = false;
        f(i,2,N){
            if(gtprime>=x) break;
            if(prime[i]==true){
                gtprime = i;
                ll j = 2;
                while(i*j<N){
                    prime[i*j] = false;
                    j++;
                }
            }
        }
        cout<<gtprime;
        cout<<endl;
    }
    return 0;
}

Measured memory_bytes: 1280
#include<cstdio>
#include<algorithm>

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

using namespace std;

struct Gate{ int cap,fil,drn,ud; };

int main(){
	for(int m,n,L;scanf("%d%d%d",&m,&n,&L),n;){
		const int OFSET=100;

		Gate gt[100];	// gate is 0-origin
		int gtpos[1204];
		rep(i,1204)	gtpos[i]=-1;
		rep(i,m){
			int x;
			scanf("%d%d%d%d%d",&x,&gt[i].cap,&gt[i].fil,&gt[i].drn,&gt[i].ud);
			gtpos[x+OFSET]=i;
		}
		int v[101];		// ship is 1-origin
		rep(i,n)	scanf("%d",v+i+1);

		// open[i] := time that j-th gate avaliable
		double open[100];
		rep(i,m){
			if(gt[i].ud==0)	open[i]=0;
			else			open[i]=1.*gt[i].cap/gt[i].fil;
		}

		// dp[i][j][k] := time that i-th ship got in  x=j (if k=0)
		//                time that i-th ship got out x=j (if k=1)
		static double dp[101][1204][2];
		rep(j,1204)rep(k,2)	dp[0][j][k]=-1e60;
		for(int i=1;i<=n;i++){
			dp[i][-i+1+OFSET][0]=0;	// initial position
			dp[i][-i+1+OFSET][1]=0;

			for(int j=-i+2;j<L+OFSET+3;j++){
				dp[i][j+OFSET][0]=max(dp[i  ][j-1+OFSET][1]+1./v[i],
									  dp[i-1][j+1+OFSET][0]);
				if(gtpos[j+OFSET]==-1){
					dp[i][j+OFSET][1]=max(dp[i  ][j  +OFSET][0],
										  dp[i-1][j+1+OFSET][1]);
				}
				else{
					int idx=gtpos[j+OFSET];
					double up  =1.*gt[idx].cap/gt[idx].fil;
					double down=1.*gt[idx].cap/gt[idx].drn;
					double start=max(dp[i][j+OFSET][0],open[idx]);
					double end=start+((gt[idx].ud==0)?up:down);
					open[idx]=start+up+down;
					dp[i][j+OFSET][1]=max(end,dp[i-1][j+1+OFSET][1]);
				}
// printf("ship %d: in  pos %2d, time %.5f\n",i,j,dp[i][j+OFSET][0]);
// printf("ship %d: out pos %2d, time %.5f\n",i,j,dp[i][j+OFSET][1]);
			}
		}

		printf("%.10f\n",dp[n][L+OFSET][0]);
	}

	return 0;
}

Measured memory_bytes: 0
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<bitset>
#include<math.h>
#include<stack>
#include<queue>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef long double db;
typedef vector<int> vi;
typedef pair<int,int> pii;
const int N=100000+100;
const db pi=acos(-1.0);
#define lowbit(x) ((x)&(-x))
#define sqr(x) (x)*(x)
#define rep(i,a,b) for (register int i=a;i<=b;i++)
#define per(i,a,b) for (register int i=a;i>=b;i--)
#define go(u,i) for (register int i=head[u],v=sq[i].to;i;i=sq[i].nxt,v=sq[i].to)
#define fir first
#define sec second
#define mkp make_pair
#define pb push_back
#define maxd 1000000007
#define eps 1e-8
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while ((ch<'0') || (ch>'9')) {if (ch=='-') f=-1;ch=getchar();}
    while ((ch>='0') && (ch<='9')) {x=x*10+(ch-'0');ch=getchar();}
    return x*f;
}

inline ll readll()
{
    ll x=0;int f=1;char ch=getchar();
    while ((ch<'0') || (ch>'9')) {if (ch=='-') f=-1;ch=getchar();}
    while ((ch>='0') && (ch<='9')) {x=x*10+(ch-'0');ch=getchar();}
    return x*f;
}

namespace My_Math{
    #define N 100200

    int fac[N+100],invfac[N+100],inv[N+100];

    int add(int x,int y) {return x+y>=maxd?x+y-maxd:x+y;}
    int dec(int x,int y) {return x<y?x-y+maxd:x-y;}
    int mul(int x,int y) {return 1ll*x*y%maxd;}
    ll qpow(ll x,int y)
    {
        ll ans=1;
        while (y)
        {
            if (y&1) ans=mul(ans,x);
            x=mul(x,x);y>>=1;
        }
        return ans;
    }
    int getinv(int x) {return qpow(x,maxd-2);}

    int C(int n,int m)
    {
        if ((n<m) || (n<0) || (m<0)) return 0;
        return mul(mul(fac[n],invfac[m]),invfac[n-m]);
    }

    void math_init()
    {
        fac[0]=invfac[0]=1;
        rep(i,1,N) fac[i]=mul(fac[i-1],i);
        invfac[N]=getinv(fac[N]);
        per(i,N-1,1) invfac[i]=mul(invfac[i+1],i+1);
        rep(i,1,N) inv[i]=mul(invfac[i],fac[i-1]);
        rep(i,1,N) inv[i]=add(inv[i],inv[i-1]);
    }
    #undef N
}
using namespace My_Math;

int n,a[N];

int main()
{
    n=read();
    rep(i,1,n) a[i]=read();
    math_init();
    int ans=0;
    rep(i,1,n) ans=add(ans,mul(a[i],add(inv[i]-1,inv[n-i+1])));
    ans=mul(ans,fac[n]);
    printf("%d\n",ans);
    return 0;
}

Measured memory_bytes: 5268
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <string>

#define pb push_back
#define all(c) (c).begin(), (c).end()

using namespace std;

#define BUFSIZE 32
char buf[BUFSIZE];
int d[4] = { 4, -4, 1, -1 };
int pow10[8] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000 };

int main()
{
	// Æè ¦¸úóÔª76543210¾Á½êÌTõoßðµÄ¨­
	// 01234567(ÅIóÔjð 76543210(úóÔ) É·éßöðS
	queue<int> q;
	map<int, int> m;
	q.push(1234567);
	m[1234567] = 0;
	while (!q.empty()) {
		int t = q.front();
		q.pop();
		if (t == 76543210) break;
		int z;
		int u = t;
		// ½Úª0©ðT·
		for (z = 0; z < 8; ++z) {
			if (u % 10 == 0) break;
			u /= 10;
		}

		for (int i = 0; i < 4; ++i) {
			int k = z + d[i];
			if (k < 0 || k > 7) continue;
			if (z == 3 && k == 4 || z == 4 && k == 3) continue;
			int next = t;
			// 0Æ×Ú·éðð·
			int d = next / pow10[k] % 10;
			next -= d * pow10[k];
			next += d * pow10[z];

			if (m.find(next) == m.end()) {
				m[next] = m[t] + 1;
				q.push(next);
			}
		}
	}
	while (fgets(buf, BUFSIZE, stdin) != NULL) {
		int ans;
		int v = 0;
		for (int i = 0; i < 15; i += 2)
			v = v * 10 + buf[i] - '0';
//		char* p = strtok(buf, " ");
//		while (p != NULL) { v = v * 10 + *p - '0'; p = strtok(NULL, " "); }
		// ãÅµÄ¨¢½àÌÉÜÜêÄ½ç»ÌlðÔµÄ¨µÜ¢
		if (m.find(v) != m.end())
			ans = m[v];
		// µÄÈ¯êÎà¤êñBFS
		// ±Á¿Í úóÔ ¨ ÅIóÔ(01234567) ÅTõ
		else {
			queue<int> q2;
			map<int, int> m2;
			q2.push(v);
			m2[v] = 0;
			while (!q2.empty()) {
				int t = q2.front();
				q2.pop();
				if (t == 1234567) { ans = m2[t]; break; }
				int z;
				int u = t;
				for (z = 0; z < 8; ++z) {
					if (u % 10 == 0) break;
					u /= 10;
				}

				for (int i = 0; i < 4; ++i) {
					int k = z + d[i];
					if (k < 0 || k > 7) continue;
					if (z == 3 && k == 4 || z == 4 && k == 3) continue;
					int next = t;
					int d = next / pow10[k] % 10;
					next -= d * pow10[k];
					next += d * pow10[z];
					/*
					if (m.find(next) != m.end()) {
						ans = m[next] + m2[t] + 1;
						break;
					}
					*/
					if (m2.find(next) == m2.end()) {
						m2[next] = m2[t] + 1;
						q2.push(next);
					}
				}
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}

Measured memory_bytes: 2020
N, X, Y = map(int, input().split())
X -= 1
Y -= 1
#print(N)
dlist = [0]*N
for k in range(1, N):
    for i in range(N-k):
        j = i + k
        usek = abs(X -i)+1+abs(j-Y)
        curk = min(k, usek)
        dlist[curk] += 1

for i in dlist[1:]:
    print(i)

Measured memory_bytes: 3444
#include <bits/stdc++.h>
// #define che
#define debug(...) fprintf(stderr,__VA_ARGS__)
#define fi first
#define se second
#define MK make_pair
#define PB push_back
using namespace std;

typedef long long LL;
typedef pair<int ,int> PII;
const int N=2e3+10;


int main(){
	#ifdef che
	freopen("input.txt","rt",stdin);
	freopen("output.txt","wt",stdout);
	#endif
	int n,m,a,b;
	scanf("%d%d%d%d", &n, &m, &a, &b);
	for (int i=1; i<=n; ++i){
		for (int j=1; j<=m; ++j) putchar(((j<=a)^(i<=b))+'0');
		puts("");
	}
	return 0;
}

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

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

    static class DReplacing {
        private static final int MAX = 100_000 + 5;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int[] a = in.readIntArray(n);
            long sum = 0;

            long[] count = new long[MAX];
            for (int i : a) {
                sum += i;
                count[i]++;
            }

            int q = in.nextInt();
            for (int query = 0; query < q; query++) {
                int b = in.nextInt(), c = in.nextInt();

                sum -= count[b] * b;
                sum += count[b] * c;
                count[c] += count[b];
                count[b] = 0;

                out.println(sum);
            }
        }

    }

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

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

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

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

        public int[] readIntArray(int n) {
            int[] x = new int[n];
            for (int i = 0; i < n; i++) {
                x[i] = nextInt();
            }
            return x;
        }

    }
}



Measured memory_bytes: 47432
/*
 *
 *
 */

#include <bits/stdc++.h>

using namespace std;

#define LOG(...) fprintf(stderr, __VA_ARGS__)
//#define LOG(...)
#define FOR(i, a, b) for(int i = (int)(a); i < (int)(b); ++i)
#define REP(i, n) for(int i = 0; i < (int)(n); ++i)
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define EXIST(s, e) ((s).find(e) != (s).end())
#define SORT(c) sort(ALL(c))
#define RSORT(c) sort(RALL(c))
#define SQ(n) (n) * (n)

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<bool> vb;
typedef vector<int> vi;
typedef vector<pii> vpi;
typedef vector<pll> vpl;
typedef vector<ll> vll;
typedef vector<vb> vvb;
typedef vector<vi> vvi;
typedef vector<vll> vvll;

struct P {
  double first;
  string second;

  bool operator <(const P& p) const {
    if(first == p.first) return second > p.second;
    return first < p.first;
  }
};

int main() {
  int n;
  while(cin >> n, n) {
    vector<P> farm;
    string l;
    REP(i, n){
      int p, a, b, c, d, e, f, s, m;
      cin >> l >> p >> a >> b >> c >> d >> e >> f >> s >> m;
      farm.push_back({(s * f * m - p) / (double)(a + b + c + (d + e) * m), l});
    }


    RSORT(farm);
    for(P s : farm) {
      cout << s.second << endl;
    }
    printf("#\n");
  }
}

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

int n;
string s,t;

int main()
{
  
  cin >> n;
  cin >> s;
  int sl =s.length();

  if(sl %2!=0){
    cout << "No";
    return 0;
  }

  rep(i,sl/2){
    t.push_back(s[i]);
  }
  //処理
    
  if(s.compare(t+t)==0){
    cout << "Yes";
    return 0;
  }

  cout << "No";
  return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(void) {
	string s;
	cin >> s;
	vector<string>t;
	//tを空にする
	for (int i(0); i < s.size(); i++) {
		if (s[i] == '0')t.push_back("0");
		else if (s[i] == '1')t.push_back("1");
		else if (s[i] == 'B') {
			if (t.empty()==false) {
				int tlength = t.size();
				t.pop_back();
			}
		}
	}
	for(int i(0);i<t.size();i++){
		cout << t[i];
	}
	cout << endl;
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits>

typedef long long int64;

static char shift_c(char bc, int sh) {
  char ac = bc + sh;
  if (ac > 'Z') {
    ac = 'A' + ac - 'Z' - 1;
  }
  return ac;
}

int main(void) {
  int n;
  std::cin >> n;
  std::string s;
  std::cin >> s;
  std::string a = s;
  for (int i = 0; i < s.size(); i++) {
    a.at(i) = shift_c(s.at(i), n);
  }
  std::cout << a << std::endl;
  return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define int             long long
 
int32_t main() {
 
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
 
 
 
  int n, k;
  cin >> n >> k;
 
  int a[n];
  int dp[n];
 
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    dp[i] = 0;
  }
  //cout << dp[0] << dp[1];
 
  for (int i = 1; i < n; i++) {
    // if (n >= k) {
    dp[i] = INT_MAX;
 
    for (int j = 1; j <= k; j++) {
      if (i - j >= 0) {
        dp[i] = min(dp[i - j] + abs(a[i] - a[i - j]), dp[i]);
 
        //cout << dp[i] << endl;
      }
      //else
    }
    //}
    //dp[i] = ans;
  }
 
  cout << dp[n - 1 ];
 
 
 
  return 0;
}

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

        typedef long long ll;
        //#define pb push_back

           int main()
         {
             int n; cin >> n;
             bool a = true;
             for(int i=1;i<=9;i++)
             {
                 for(int j=1;j<=9;j++)
                 {
                     if(i*j==n){
                        a =false;
                     }
                 }
             }
             if(!a) cout << "Yes" << '\n';
             else cout << "No" << '\n';
         }


Measured memory_bytes: 256
num = int(input())
count = 0
num_list = list(map(int,input().split()))
while(1):
  dummy = max(num_list)
  if dummy == 0:
    break
  flag = "nocheck"
  for i in range(num):
    if num_list[i] == dummy:
      num_list[i] -= 1
      flag = "check"
    else:
      if flag == "check":
        flag = "nocheck"
        break
  count += 1
print(count)

Measured memory_bytes: 3064
#include <cassert>

#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#define rep(i,j,k) for(int i=(int)j;i<(int)k;i++)
#define ll long long
#define Sort(v) sort(all(v))
#define INF 1000000000
#define END return 0
#define pb push_back
#define se second
#define fi first
#define pb push_back
#define all(v) (v).begin() , (v).end()
#define MP make_pair
#define MOD 1000000007LL;
using namespace std;
int day[12]={31,28,31,30,31,30,31,31,30,31,30,31};


int main(){
    int n;
    cin>>n;
    if(n==1)cout<<"Hello World"<<endl;
    else {
        int a,b;cin>>a>>b;
        cout<<a+b<<endl;
    }

    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;

int main(void) {
    int N;
    cin >> N;
    vector<int> A(N+1);
    for(int i=1; i<=N; i++) {
        cin >> A[i];
    }

    vector< vector<int> > psum(20, vector<int>(N+1));
    for(int i=1; i<=N; i++) {
        for(int bit=0; bit<20; bit++) {
            if((A[i]>>bit) & 1) {
                psum[bit][i] = psum[bit][i-1] + 1;
            } else {
                psum[bit][i] = psum[bit][i-1];
            }
        }
    }

    vector<int> zero(N+2);
    for(int i=N; i; i--) {
        if(A[i] == 0) {
            zero[i] = zero[i+1] + 1;
        }
    }

    int64_t ans = N;
    for(int l=1; l<=N; l++) {
        for(int r=l+1; r<=N; r++) {
            bool ok = true;
            if(A[r] == 0) {
                ans += zero[r];
                r += zero[r] - 1;
            } else {
                for(int bit = 0; bit<20; bit++) {
                    if((psum[bit][r-1]-psum[bit][l-1])%2 > (psum[bit][r]-psum[bit][l-1])%2) {
                        ok = false;
                        break;
                    }
                }
                if(ok) {
                    ans++;
                } else {
                    break;
                }
            }
        }
    }

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


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

string s;
bitset<10> cutoff;

int main() {
    cin.sync_with_stdio(0); cin.tie(0);
    cin >> s;
    
    int n = s.size() - 1;
    ll ans = 0;
    for (int i = 0; i < (1 << n); i++) {
        cutoff.reset();
        for (int j = 0; j < n; j++) {
            if (i & (1 << j)) {
                cutoff[j] = 1;
            }
        }

        ll cur = 0, cpow = 0;
        for (int j = n; j >= 0; --j) {
            cur += (s[j] - '0') * pow(10, cpow);
            cpow++;
            if (cutoff[n - j] || !j) {
                ans += cur;
                cpow = 0;
                cur = 0;
            }
        }
    }
    cout << ans;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
//#define cerr if (false) cerr
#define db(x) cerr << #x << "=" << x << endl
#define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl
#define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl
#define dbv(v) cerr << #v << "="; for (auto _x : v) cerr << _x << ", "; cerr << endl
#define dba(a, n) cerr << #a << "="; for (int _i = 0; _i < (n); ++_i) cerr << a[_i] << ", "; cerr << endl
template <typename A, typename B>
ostream& operator<<(ostream& os, const pair<A, B>& x) {
	return os << "(" << x.first << "," << x.second << ")";
}
typedef long long ll;
typedef long double ld;
const int MOD = 998244353;
struct Mint {
	int val;
	Mint() { val = 0; }
	Mint(const ll& x) {
		val = (-MOD <= x && x < MOD) ? x : x % MOD;
		if (val < 0) val += MOD;
	}
	friend bool operator==(const Mint& a, const Mint& b) { return a.val == b.val; }
	friend bool operator!=(const Mint& a, const Mint& b) { return !(a == b); }
	friend bool operator<(const Mint& a, const Mint& b) { return a.val < b.val; }
	Mint& operator+=(const Mint& m) { if ((val += m.val) >= MOD) val -= MOD; return *this; }
	Mint& operator-=(const Mint& m) { if ((val -= m.val) < 0) val += MOD; return *this; }
	Mint& operator*=(const Mint& m) { val = (ll)val * m.val % MOD; return *this; }
	friend Mint modex(Mint a, ll p) {
		assert(p >= 0);
		Mint ans = 1;
		for (; p; p >>= 1, a *= a) if (p & 1) ans *= a;
		return ans;
	}
	Mint& operator/=(const Mint& m) { return *this *= modex(m, MOD - 2); }
	Mint& operator++() { return *this += 1; }
	Mint& operator--() { return *this -= 1; }
	Mint operator++(int) { Mint result(*this); *this += 1; return result; }
	Mint operator--(int) { Mint result(*this); *this -= 1; return result; }
	Mint operator-() const { return Mint(-val); }
	friend Mint operator+(Mint a, const Mint& b) { return a += b; }
	friend Mint operator-(Mint a, const Mint& b) { return a -= b; }
	friend Mint operator*(Mint a, const Mint& b) { return a *= b; }
	friend Mint operator/(Mint a, const Mint& b) { return a /= b; }
	friend ostream& operator<<(ostream& os, const Mint& x) { return os << x.val; }
};
const int MAXN = 20000005;
Mint fac[MAXN], invfac[MAXN];
Mint binom(ll a, ll b) {
	if (b < 0) return 0;
	if (b > a) return 0;
	return fac[a] * invfac[b] * invfac[a - b];
}
int main() {
	fac[0] = 1;
	for (int i = 1; i < MAXN; ++i)
		fac[i] = fac[i - 1] * i;
	invfac[MAXN - 1] = 1 / fac[MAXN - 1];
	for (int i = MAXN - 2; i >= 0; --i)
		invfac[i] = invfac[i + 1] * (i + 1);
	int n, A, B;
	scanf("%d%d%d", &n, &A, &B);
	if (A > B) swap(A, B);
	if (!B) {
		printf("1\n");
		return 0;
	}
	Mint ans = 0;
	for (int k = 0; k <= A; ++k) {
		if (B + k > n) break;
		Mint v = binom(k + B - 1, k) - binom(k + B - 1, k - 1);
		int has = n - B - k;
		int buckets = A - k + 1;
		Mint w = binom(has + buckets - 1, buckets - 1);
		if (k < A) {
			w -= binom(has + buckets - 2, buckets - 2);
		}
		ans += v * w;
	}
	printf("%d\n", ans.val);
}


Measured memory_bytes: 156544
#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main(){
  int n;cin >> n;
  int a[100005];
  for(int i=0;i<n;i++){
    cin >> a[i];
  }
  int ans = 0;
  for(int i=0;i<n;i++){
    if(a[a[i]-1]==i+1)ans++;
  }
  cout << ans/2 << endl;
}

Measured memory_bytes: 640
#![allow(non_snake_case, unused)]
use std::cmp::*;
use std::collections::*;
use std::f64::consts::*;

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

    ($next:expr, mut $var:ident : $t:tt $($r:tt)*) => {
        let mut $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, [ $t:tt ]) => {
        {
            let len = read_value!($next, usize);
            (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
        }
    };

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

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

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

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

fn main() {
    input!{
        n: usize,
        s: [String; n],
    }
    let mut v = vec![0i64; 3];
    let mut cnt = 0i64;
    for i in 0..n {
        let acc = &s[i];
        if acc.starts_with("B") && acc.ends_with("A") {
            v[1] += 1;
        } else if acc.starts_with("B") {
            v[0] += 1;
        } else if acc.ends_with("A") {
            v[2] += 1;
        }
        cnt += acc.match_indices("AB").count() as i64;
    }
    if v[1] == 0 {
        cnt += min(v[0], v[2])
    } else if v[0]+v[2] > 0 {
        cnt += v[1] + min(v[0], v[2])
    } else {
        cnt += v[1] - 1
    }
    println!("{}", cnt);

}


Measured memory_bytes: 4352