akhauriyash/Code-Regression huggingface dataset:
from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
import string

def get_int():
    return int(stdin.readline().strip())


def get_tuple():
    return map(int, stdin.readline().split())


def get_list():
    return list(map(int, stdin.readline().split()))


def solve():
    return

def main():
    n = get_int()
    terms = 0
    i = 1
    while n>terms:
        terms += 26**i
        i += 1
    # print(i, terms, old_terms)
    i -= 2
    ans = ""
    n  = n-(terms-26**(i+1))-1
    if n==0: ans = "a"*(i+1)
    alphabets = list(string.ascii_lowercase)
    while n>0:
        index,n = divmod(n,26**i)
        i -= 1
        #print(index, i, n,ans)
        ans += alphabets[index]
        if n==0 and i==0: ans += "a"

    print(ans)



TestCases = False

if TestCases:
    for i in range(get_int()):
        main()
else:
    main()


Measured memory_bytes: 10076
# from itertools import product

# n = int(input())

# edge_comb = []
# for i in range(1,n):
#     for j in range(i+1,n+1):
#         edge_comb.append((i,j))


# comb_n = len(edge_comb)
# ite = product(range(2),repeat=comb_n)
# ite = list(ite)
# for it in ite:
#     it = list(it)
#     gl = [ [] for _ in range(n+1) ]
#     for i,v in enumerate(it):
#         if v == 1:
#             edge = edge_comb[i]
#             a,b = edge
#             gl[a].append(b)
#             gl[b].append(a)
    
#     sums = [0]*(n+1)
#     for i in range(n+1):
#         sums[i] = sum(gl[i])
    
#     val = sums[1]
#     for i in range(2,n+1):
#         if sums[i] != val:
#             break
#     else:
#         print(gl)

n = int(input())
gl = [ [] for _ in range(n+1) ]

if n%2 == 0:
    ng = n+1
    for i in range(1,n//2+1):
        for j in range(1,n+1):
            # if i+j != ng:
            if i != j and n+1-i != j:
                gl[i].append(j)
                gl[n+1-i].append(j)
else:
    ng = n
    for i in range(1,n//2+1):
        for j in range(1,n+1):
            if i != j and n-i != j:
                gl[i].append(j)
                gl[n-i].append(j)  
    gl[n] = list(range(1,n))

cnt = 0
for g in gl:
    cnt += len(g)

s = set()
print(cnt//2)
for i,g in enumerate(gl):
    if i == 0: continue
    for v in g:
        if (v,i) in s: continue
        print(i,v)
        s.add((i,v))

Measured memory_bytes: 74080
#include <bits/stdc++.h>
using namespace std;
#define vi vector<int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define ii pair<int,int>
const int MOD = 1e9 + 7;

int main() {
   ios_base::sync_with_stdio(0); cin.tie(0);
   int a,b;
   cin>>a>>b;
   if(a < 2 * b)
        cout<<0<<"\n";
   else
        cout<<a-2 * b<<"\n";
  
   return 0;   
}

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

template<typename T>
struct BIT {
  vector<T> data;
  BIT() {}
  BIT(int n) : data(n+1, 0) {}
  void init(int n) { data.assign(n+1, 0); }
  T sum(int ed) const {
    for(T res(0); ; ed &= ed-1) if(ed) res += data[ed]; else return res;
  }
  void add(int i, const T& x) {
    for(++i; i < (int)data.size(); i += i&-i) data[i] += x;
  }
};

struct K {
  char c;
  int v;
};

int n;
K vs[4010];
int toPos[2][2010];


BIT<int> bit;
int memo[2010][2010];
int solve(int nb, int nw) {
  int& res = memo[nb][nw];
  if(res < 0) {
    if(nb + nw == 2*n) {
      res = 0;
    } else {
      res = 1000000000;
      if(nb < n) { // ここに黒を持ってくる
        int pos = toPos[0][nb];
        int cost = pos-bit.sum(pos);
        bit.add(pos, 1);
        res = min(res, cost + solve(nb+1, nw));
        bit.add(pos, -1);
      }
      if(nw < n) { // ここに白を持ってくる
        int pos = toPos[1][nw];
        int cost = pos-bit.sum(pos);
        bit.add(pos, 1);
        res = min(res, cost + solve(nb, nw+1));
        bit.add(pos, -1);
      }
    }
  }
  return res;
}


int main(void) {
  scanf("%d", &n);
  REP(i, 2*n) {
    scanf(" %c %d", &vs[i].c, &vs[i].v);
    --vs[i].v;
    toPos[vs[i].c == 'B'][vs[i].v] = i;
  }
  memset(memo, -1, sizeof memo);
  bit.init(2*n);
  int res = solve(0, 0);
  printf("%d\n", res);
  return 0;
}


Measured memory_bytes: 16384
#include <bits/stdc++.h>
using namespace std;
 
int main(){
    long double n, m;
    cin >> n >> m;
    long double ans = 0;
    for(int i=1; i<=1000000; i++){
        ans += (powl(0.5, m) * powl(1-powl(0.5, m), i-1) * i * (m*1900.0 + (n-m)*100.0));
    }
    cout << round(ans) << endl;
    return 0;
}

Measured memory_bytes: 256
#pragma GCC optimize ("O3")
#pragma GCC target ("tune=native")
#pragma GCC target ("avx")

#include <bits/stdc++.h>

// 汎用マクロ
#define ALL_OF(x) (x).begin(), (x).end()
#define REP(i,n) for (long long i=0, i##_len=(n); i<i##_len; i++)
#define RANGE(i,is,ie) for (long long i=(is), i##_end=(ie); i<=i##_end; i++)
#define DSRNG(i,is,ie) for (long long i=(is), i##_end=(ie); i>=i##_end; i--)
#define UNIQUE(v) { sort((v).begin(), (v).end()); (v).erase(unique((v).begin(), (v).end()), (v).end()); }
template<class T> bool chmax(T &a, const T &b) {if (a < b) {a = b; return true;} return false; }
template<class T> bool chmin(T &a, const T &b) {if (a > b) {a = b; return true;} return false; }
#define INF 0x7FFFFFFF
#define LINF 0x7FFFFFFFFFFFFFFFLL
#define Yes(q) (q ? "Yes" : "No")
#define YES(q) (q ? "YES" : "NO")
#define DUMP(q) cerr << "[DEBUG] " #q ": " << (q) << " at " __FILE__ ":" << __LINE__ << endl
#define DUMPALL(q) { cerr << "[DEBUG] " #q ": ["; REP(dumpall_i, (q).size()) { cerr << q[dumpall_i] << (dumpall_i == (q).size() - 1 ? "" : ", "); } cerr << "] at " __FILE__ ":" << __LINE__ << endl; }
template<class T> T gcd(const T &a, const T &b) { return a < b ? gcd(b, a) : b ? gcd(b, a % b) : a; }
template<class T> T lcm(const T &a, const T &b) { return a / gcd(a, b) * b; }

// gcc拡張マクロ
#define popcount __builtin_popcount
#define popcountll __builtin_popcountll

// エイリアス
using  ll = long long;
using ull = unsigned long long;
using  ld = long double;
using namespace std;

// モジュール


// 処理内容
int main() {
    
    string s; cin >> s;
    ll sl = s.size();

    ll wins = 0;
    REP(i, sl) if (s[i] == 'o') wins++;

    cout << YES(wins + 15 - sl >= 8) << endl;
    
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define int long long
using namespace std;
int32_t main()
{
    int n,m;
    cin>>n>>m;
    int l,r,x=-1,y=INT_MAX;
    for(int i=0;i<m;++i)
    {
        cin>>l>>r;
        if(l>x)
        x=l;
        if(r<y)
        y=r;
    }
    if(y-x+1<0)
    cout<<0;
    else 
    cout<<y-x+1;
}

Measured memory_bytes: 3592
#include <iostream>
#include <string>
#include<vector>
#include<algorithm>
#include<utility>
#include<queue>
#include<math.h>
#include<stack>
#define INF 2e9
#define rep(i,m) for(int i=0;i<m;i++)
#define repn(i,n,m) for(int i=n;i<m;i++)

using namespace std;

int main()
{
	int s, w;
	cin >> s >> w;

	if (s > w)cout << "safe" << endl;
	else cout << "unsafe" << endl;
	return 0;
}

Measured memory_bytes: 3632
a, b, c, x, y = map(int, input().split())
if a+b <= 2*c:
    print(a*x + b*y)
else:
    if x > y:
        if a < 2*c:
            print(2*y*c + (x-y)*a)
        else:
            print(2*x*c)
    else:
        if b < 2*c:
            print(2*x*c + (y-x)*b)
        else:
            print(2*y*c)

Measured memory_bytes: 38740
#https://atcoder.jp/contests/abc079/tasks/abc079_c
ABCD = input()
A = int(ABCD[0])
B = int(ABCD[1])
C = int(ABCD[2])
D = int(ABCD[3])
ans  = str(A)
for ab in range(2):
    for bc in range(2):
        for cd in range(2):
            sum = A
            if ab:
                sum +=B
            else:
                sum -=B
            if bc:
                sum +=C
            else:
                sum -=C
            if cd:
                sum +=D
            else:
                sum -=D
            if sum == 7:
                A_B_C_D = ABCD[0] + str(ab) +ABCD[1]+ str(bc) +ABCD[2]+ str(cd) +ABCD[3]
                for i in range(1,6,2):
                    if int(A_B_C_D[i]):
                        ans += "+"
                    else:
                        ans += "-"
                    ans += A_B_C_D[i+1]
                break
        else:
            continue
        break
    else:
        continue
    break
    
print(ans + "=7")

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

int main(){
    string s;
    while(getline(cin, s)){
        if(s == "END OF INPUT") break;
        int c = 0;
        for(int i = 0; i < s.length(); i++){
            if(s[i] != ' ') c++;
            else   cout << c, c = 0;
        }
        cout << c << endl;
    }   
    return 0; 
}


Measured memory_bytes: 3116
# https://atcoder.jp/contests/arc074/tasks/arc074_b

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n = int(input())
    al = list(map(int, input().split()))

    # front
    front = []
    front_sum = 0
    for i in range(n):
        front_sum += al[i]
        heappush(front, al[i])

    front_sums = [front_sum]
    for i in range(n, n * 2):
        minimum = heappop(front)
        if minimum < al[i]:
            front_sum += al[i] - minimum
            heappush(front, al[i])
        else:
            heappush(front, minimum)
        front_sums.append(front_sum)

    # back
    back = []
    back_sum = 0
    for i in range(n * 2, n * 3):
        back_sum += al[i]
        heappush(back, -al[i])

    back_sums = [back_sum]
    for i in range(n * 2 - 1, n - 1, -1):
        maximum = -heappop(back)
        if maximum > al[i]:
            back_sum += al[i] - maximum
            heappush(back, -al[i])
        else:
            heappush(back, -maximum)
        back_sums.append(back_sum)

    back_sums.reverse()

    # print(front_sums)
    # print(back_sums)

    ans = -10**20
    for f, b in zip(front_sums, back_sums):
        ans = max(ans, f - b)

    print(ans)


if __name__ == '__main__':
    main()


Measured memory_bytes: 120124
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def fact(n):
        if n < 4:
            return [n,1]
        i = 2
        res = [1,n]
        while i*i <= n:
            if n%i == 0:
                res.append(i)
                m = n//i
                if m != i:
                    res.append(m)
            i += 1
        res.sort(reverse = True)
        return res
    n,k = LI()
    a = LI()
    s = sum(a)
    f = fact(s)
    for i in f:
        s = [j%i for j in a]
        s.sort()
        s = list(accumulate(s))
        l = 0
        r = n
        while r > l+1:
            j = (l+r) >> 1
            sl = s[j]
            sr = i*(n-j-1)-s[-1]+s[j]
            if sl <= sr:
                l = j
            else:
                r = j
        sl = s[l]
        sr = i*(n-l-1)-s[-1]+s[l]
        if sl == sr:
            if sl <= k:
                print(i)
                return
    return

#Solve
if __name__ == "__main__":
    solve()


Measured memory_bytes: 42604
import sys
input = lambda: sys.stdin.readline().rstrip()

def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = [0] + list(map(int , input().split()))
    c = [0] + list(map(int , input().split()))
    ans = 0
    for i in range(n):
        ans += b[a[i]]
        if i > 0 and a[i-1] == a[i] - 1:
            ans += c[a[i-1]]
    print(ans)

if __name__ == '__main__':
    main()

Measured memory_bytes: 9232
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <string>
#include <algorithm>

int main()
{
	int N;
	std::cin >> N;
	std::set<std::string> S;
	for (int i = 0; i < N; ++i) {
		std::string s;
		std::cin >> s;
		S.insert(s);
	}
	std::cout << S.size() << std::endl;
	return 0;
}

Measured memory_bytes: 19192
#include <iostream>
#include <vector>
#include <string>

#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define rer(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define reu(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3fLL;
typedef long long ll;
template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if (x < y) x = y; }

using namespace std;


int main()
{
	string s;
	cin >> s;
	if (s.size() < 4) {
		cout << "No" << endl;
		return 0;
	}
	if ((s[0] == 'Y') && (s[1] == 'A') && (s[2] == 'K') && (s[3] == 'I')) {
		cout << "Yes" << endl;
		return 0;
	}
	cout << "No" << endl;
	return 0;
}

Measured memory_bytes: 256
#include<stdio.h>

#define N 100
#define WHITE 0
#define GRAY 1
#define BLACK 2

int n,t;
int color[N],d[N],f[N];
int M[N][N];

void idfs(int);

void dfs();

int main(){
  int i,j,v,u,k;

  scanf("%d",&n);

  for(i=0;i<n;i++){
    for(j=0;j<n;j++){
      M[i][j]=0;
    }
  }

  for(i=0;i<n;i++){
    scanf("%d%d",&u,&k);
    for(j=0;j<k;j++){
      scanf("%d",&v);
      M[u-1][v-1]=1;
    }
  }

  dfs();
  return 0;
}

void idfs(int u){
  int v;

  color[u]=GRAY;
  d[u]=++t;

  for(v=1;v<n;v++){
    if(M[u][v]==0){
      continue;
    }
    if(color[v]==WHITE){
      idfs(v);
    }
  }

  color[u]=BLACK;
  f[u]=++t;

}

void dfs(){
  int i;

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

  t=0;
  for(i=0;i<n;i++){
    if(color[i]==WHITE){
      idfs(i);
    }
    }

    for(i=0;i<n;i++){
      printf("%d %d %d\n",i+1,d[i],f[i]);
}
}


    
    
  



Measured memory_bytes: 2060
N, K = map( int, input().split())
A = list( map( int, input().split()))
# 1の個数をそれぞれの桁でカウントしたい
V = [0]*41
for a in A:
    for i in range(40,-1,-1):
        if a%2 == 0:
            pass
        else:
            V[i] += 1
        a //= 2
        if a == 0:
            break
W = [0]*41
for i in range(40,-1,-1):
    if K%2 == 0:
        pass
    else:
        W[i] += 1
    K //= 2
    if K == 0:
        break
ans = 0
check = 0
for i in range(41):
    if W[i] == 1:
        if V[i] > N - V[i]:
            ans += (2**(40-i))*V[i]
            check = 1
        else:
            ans += (2**(40-i))*(N-V[i])
    else:
        if check == 0:
            ans += (2**(40-i))*V[i]
        else:
            if V[i] > N - V[i]:
                ans += (2**(40-i))*V[i]
            else:
                ans += (2**(40-i))*(N-V[i])
print( ans)


Measured memory_bytes: 14620
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i=0;i<n;++i)
#define rep1(i,n) for(int i=1;i<=n;++i)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout<< (x) << " "

int main(){
    int n;cin>>n;
    vector<int> c(n);rep(i,n)cin>>c[i];
    sort(c.begin(), c.end());
    int a=0,b=0;
    rep(i,n){
        (i%2==0)?a+=c[i]:b+=c[i];
    }
    co(abs(a-b));
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define tag "spoj"
#define maxn 10007
#define oo 2000000007
#define meset(a,x) memset(a,x,sizeof(a))
#define loop(x) for(int LoOpEr=x;LoOpEr-->0;)
///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
int main()
{
    #ifdef dmdd
    freopen(tag".inp","r",stdin); freopen(tag".out","w",stdout);
    #endif // dmdd
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    long long l,r;

    cin>>l>>r;

    if(r-l+1<=5000)
    {
        long long rep=oo;
        for(int i=l;i<=r;i++)
            for(int j=l;j<i;j++)
                rep=min(rep,1LL*(i%2019)*(j%2019)%2019);
        cout<<rep;
    }
    else cout<<0;
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
// #include <algorithm>
// #include <set>
// #include <cmath>
// #include <string>

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


int main(int argc, char const *argv[]) {
    int N;
    cin >> N;
    if (N % 10 == 7 || (N / 10) % 10 == 7 || (N / 100) == 7) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
    return 0;
}


Measured memory_bytes: 3592
//
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef pair<ll, P>IP;
typedef vector<ll> V;
typedef vector<V> V2;
typedef vector<vector<P> > G;
void g_dir(G &graph, ll a, ll b, ll w = 1){graph[a].push_back(P(b, w));}
void g_undir(G &graph, ll a, ll b, ll w = 1){g_dir(graph, a, b, w);g_dir(graph, b, a, w);}
#define rep(i, n) for(ll (i) = 0; (i) < (n); (i)++)
#define rep1(i, n) for(ll (i) = 1; (i) <= (n); (i)++)
#define rrep(i, n) for(ll (i) = (n) - 1; (i) >= 0; (i)--)
#define rrep1(i, n) for(ll (i) = (n); (i) >= 1; (i)--)
template<class T> void chmax(T &a, const T &b){if(a < b){a = b;}}
template<class T> void chmin(T &a, const T &b){if(a > b){a = b;}}
const ll INF = 1145141919;
const ll MOD = 1000000007;
const ll NUM = 101010;

int main(){

    ll N;
    cin >> N;
    V v(N + 1, 0);
    rep(i, N - 1){
        ll a;
        cin >> a;
        v[a]++;
    }
    rep1(i, N)cout << v[i] << endl;

    return 0;
}

Measured memory_bytes: 4844
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <cstdio>
#include <cmath>

using namespace std;

int main(void)
{
    string s;
    while(getline(cin, s)) {
        for(int i=0; i<26; i++) {
            for(int j=0; j<(int)s.size(); j++) {
                if('a' <= s[j] && s[j] <='z') {
                    s[j] = (s[j] - 'a' + 1) % 26 + 'a';
                }
            }
            if(s.find("the") != string::npos || s.find("this") != string::npos ||
                    s.find("that") != string::npos)
                break;
        }
        cout << s << endl;
    }

    return 0;
}

Measured memory_bytes: 1176
#include<bits/stdc++.h>
using namespace std;
int a,b,c,i,j,n,s;
int main()
{
    scanf("%d%d%d%d",&a,&b,&c,&n);
    for (i=0;i<=a;i++)
     for (j=0;j<=b;j++)
      if (n-i*500-j*100>=0&&n-i*500-j*100<=c*50) s++;
    printf("%d\n",s);
    return 0;
}

Measured memory_bytes: 256
n, m = map(int, input().split())
s = [[] for _ in [0]*n]
for _ in [0]*m:
    p, _s = input().split()
    s[int(p)-1] += [_s]
ans = 0
pena = 0
for i in s:
    if 'AC' in i:
        ans += 1
        pena += i[:i.index('AC')].count('WA')
print(ans, pena)

Measured memory_bytes: 21128
#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
using namespace std;
typedef long long int ll;
typedef pair<int,int> P;
#define yn {puts("Yes");}else{puts("No");}

const int MAX_N = 1 << 19;

// セグメント木を持つグローバル配列
int nn, dat[2 * MAX_N - 1];

// 初期化
void init(int n_){
    // n_が小さいときの変な挙動を防ぐ
    if(n_ < 10)n_ = 10;
    // 簡単のため要素数を2のべき乗に
    nn = 1;
    while(nn < n_)nn *= 2;

    // 全ての値をINT_MAXに
    for(int i = 0; i < 2 * nn - 1; i++)dat[i] = INT_MAX;
}

// k番目の値(0-indexed)をaに変更
void update(int k, int a){
    // 葉の接点
    k += nn - 1;
    dat[k] = a;
    // 登りながら更新
    while(k > 0){
        k = (k - 1) / 2;
        dat[k] = min(dat[k * 2 + 1], dat[k * 2 + 2]);
    }
}

// [a,b)の最小値を求める
// 後ろのほうの引数は、計算の簡単のための引数。
// kは節点の番号、l, rはその節点が[l, r)に対応づいていることを表す。
// したがって、外からはquery(a, b, 0, 0, nn)として呼ぶ。
int query(int a, int b, int k, int l, int r){
    // [a, b)と[l, r)が交差しなければ、INT_MAX
    if (r <= a || b <= l)return INT_MAX;

    // [a, b)が[l, r)を完全に含んでいれば、この節点の値
    if (a <= l && r <= b)return dat[k];
    else {
        // そうでなければ、2つの子の最小値
        int vl = query(a, b, k * 2 + 1, l, (l + r) / 2);
        int vr = query(a, b, k * 2 + 2, (l + r) / 2, r);
        return min(vl, vr);
    }
}

const ll MOD = 998244353;

int main() {
    int n;
    cin >> n;
    vector<P> v;
    rep(i,n){
        int x, d;
        cin >> x >> d;
        v.push_back(P(x,d));
    }
    v.push_back(P(2000000007, 1));

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

    init(n+1);

    int x[n+1] = {};
    rep(i,n+1)x[i] = v[i].first;

    update(n, -n);
    drep(i,n){
        int ite = lower_bound(x, x+n+1, v[i].first + v[i].second) - x;
        int tmp = query(i,ite,0,0,nn);
        if(tmp > 1234567)tmp = -i;
        update(i, tmp);
    }

    ll dp[n+1] = {};
    dp[0] = 1;
    rep(i,n){
        dp[i+1] += dp[i];
        dp[i+1] %= MOD;
        int tmp = -query(i,i+1,0,0,nn);
        dp[tmp+1] += dp[i];
        dp[tmp+1] %= MOD;
    }

    cout << dp[n] << endl;
    return 0;
}
 
 


Measured memory_bytes: 8432
def gcd(a, b):
	"""Compute the greatest common divisor of a and b"""
	while b > 0:
		a, b = b, a % b
	return a

def lcm(a, b):
	"""Compute the lowest common multiple of a and b"""
	return a * b // gcd(a, b)

def resolve():
	n = int(input())
	T = []
	for _ in range(n):
		T.append(int(input()))
	ans = 1
	for i in range(n):
		ans = lcm(ans, T[i])
	print(int(ans))
resolve()

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

using namespace std;
using vi = vector<int>;
using ll = long long;

int main(void)
{
    int n;
    ll  cur_killed, total_killed;
    vi  a, b;
    cin >> n;
    a.resize(n + 1), b.resize(n);

    for (auto &ai : a)
        cin >> ai;
    for (auto &bi : b)
        cin >> bi;

    total_killed = 0;
    for (int i = 0; i < n; ++i)
    {
        cur_killed = min(b[i], a[i] + a[i + 1]);
        total_killed += cur_killed;
        a[i + 1] -= max(0LL, cur_killed - a[i]);
    }

    cout << total_killed << endl;

    return 0;
}


Measured memory_bytes: 4004
/* template.cpp {{{ */
#include <bits/stdc++.h>
using namespace std;
#define get_macro(a, b, c, d, name, ...) name
#define rep(...) get_macro(__VA_ARGS__, rep4, rep3, rep2, rep1)(__VA_ARGS__)
#define rrep(...) get_macro(__VA_ARGS__, rrep4, rrep3, rrep2, rrep1)(__VA_ARGS__)
#define rep1(n) rep2(i_, n)
#define rep2(i, n) rep3(i, 0, n)
#define rep3(i, a, b) rep4(i, a, b, 1)
#define rep4(i, a, b, s) for (ll i = (a); i < (ll)(b); i += (ll)(s))
#define rrep1(n) rrep2(i_, n)
#define rrep2(i, n) rrep3(i, 0, n)
#define rrep3(i, a, b) rrep4(i, a, b, 1)
#define rrep4(i, a, b, s) for (ll i = (ll)(b) - 1; i >= (ll)(a); i -= (ll)(s))
#define each(x, c) for (auto &&x : c)
#define fs first
#define sc second
#define all(c) begin(c), end(c)
using ui = unsigned;
using ll = long long;
using ul = unsigned long long;
using ld = long double;
const int inf = 1e9 + 10;
const ll inf_ll = (ll)1e18 + 10;
const ll mod = 1e9 + 7;
const ll mod9 = 1e9 + 9;
const int dx[]{-1, 0, 1, 0, -1, 1, 1, -1};
const int dy[]{0, -1, 0, 1, -1, -1, 1, 1};
template<class T, class U> void chmin(T &x, const U &y){ x = min<T>(x, y); }
template<class T, class U> void chmax(T &x, const U &y){ x = max<T>(x, y); }
struct prepare_ { prepare_(){ cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(12); } } prepare__;
/* }}} */

string to_string(int x, int len){
  string s(len, '0');
  rrep(i, len){
    s[i] = '0' + x % 10;
    x /= 10;
  }
  return s;
}

int a[10][10];

int h(string s){
  int x = 0;
  each(c, s) x = a[x][c - '0'];
  return x;
}

int main(){
  rep(i, 10) rep(j, 10) cin >> a[i][j];
  int res = 0;
  rep(i, 10000){
    string s = to_string(i, 4);
    s += '0' + h(s);
    bool f = false;
    rep(j, 5) rep(k, 10){
      string t = s;
      t[j] = '0' + k;
      f |= s != t && h(t) == 0;
    }
    rep(j, 4){
      string t = s;
      swap(t[j], t[j + 1]);
      f |= s != t && h(t) == 0;
    }
    if (f) res++;
  }
  cout << res << endl;
}

Measured memory_bytes: 3204
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 sum=0;
        int rec= 101;
        for(int i=0;i<N;i++){
            sum += a[i];
            if(a[i]%10!=0) rec=Math.min(rec,a[i]);
        }
        if(sum%10!=0) System.out.println(sum);
        else{
            int ans = 0;
            if(rec!=101) ans = sum-rec;
            System.out.println(ans);
        }
    }
}
 

Measured memory_bytes: 22612
#include <stdio.h>
#define swap(type, a, b) do{ type t = a; a = b; b = t; }while(0)

void quick(int array[], int adres[], int left, int right){
  int pl = left, pr = right, x = array[(left + right) / 2];
  do{
    while(array[pl] > x)  pl++;
    while(array[pr] < x)  pr--;
    if(pl <= pr){
      swap(int, array[pl], array[pr]);
      swap(int, adres[pl], adres[pr]);
      pl++, pr--;
    }
  }while(pl <= pr);
  if(pl < right)  quick(array, adres, pl, right);
  if(pr > left)  quick(array, adres, left, pr);
}			    

int main(){
  int n;  scanf("%d", &n);
  int a[200003];
  int adres[200003];
  for(int i=1; i<=n; i++){
    scanf("%d", &a[i]);
    adres[i] = i;
  }
  quick(a, adres, 1, n);
  for(int i=1; i<=n; i++)
    if(adres[1] == i)
      printf("%d\n", a[2]);
    else
      printf("%d\n", a[1]);
  return 0;
}  


Measured memory_bytes: 3072
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long
#define pll pair < ll , ll >
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define ld long double
#define endl "\n"
using namespace std;
using namespace __gnu_pbds;
ll M = 1e9 + 7;

typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;

int main()
{

    ios_base :: sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int p;
    cin >> p;
    cout << fixed << setprecision(12) << p*3.141592653589793238462*2;
}


Measured memory_bytes: 3800
n, m = gets.split.map(&:to_i)
a = m.times.map { gets.to_i }.uniq

unless a.size < 2 || a[0..-2].zip(a[1..-1]).all? {|b, c| c - b > 1 }
  puts 0
  exit
end

@fibonatti = [1, 1]

def fibonatti(i)
  return @fibonatti[i] if @fibonatti[i]
  @fibonatti.size.step(i) do |k|
    @fibonatti[k] = @fibonatti[k - 1] + @fibonatti[k - 2]
  end
  @fibonatti[i]
end

ans = ([-1] + a).zip(a + [n+1]).inject(1) do |memo, (current, next_)|
  memo * fibonatti(next_ - current - 2)
end

puts (ans % 1_000_000_007)

Measured memory_bytes: 433020
#include "iostream"
#include "climits"
#include "list"
#include "queue"
#include "stack"
#include "set"
#include "functional"
#include "algorithm"
#include "math.h"
#include "utility"
#include "string"
#include "map"
#include "unordered_map"
#include "iomanip"
#include "random"

using namespace std;
const long long int MOD = 1000000007;

long long int power(long long int x, long long int n, long long int M) {
	long long int tmp = 1;

	if (n > 0) {
		tmp = power(x, n / 2, M);
		if (n % 2 == 0) tmp = (tmp*tmp) % M;
		else tmp = (((tmp*tmp) % M)*x) % M;
	}
	return tmp;
}

long long int N, M, K, Q, W, H;
long long int ans;


int main() {
	ios::sync_with_stdio(false);
	cin >> N >> M >> K;
	cout << max(abs(M - K) - N, (long long int)0) << endl;
	return 0;
}

Measured memory_bytes: 256
def get_ptr(s, r_start):
    r_end = 0
    l_start = 0
    l_end = 0
    is_start = False
    for i in range(r_start, len(s)):
        if s[i] == 'L' and not is_start:
            r_end = i - 1
            l_start = i
            is_start = True
        if is_start and (i == len(s) - 1 or s[i] == 'R'):
            if i == len(s) - 1:
                l_end = i
            else:
                l_end = i - 1
            break
    return r_end, l_start, l_end


s = input()

ret = [0] * len(s)

is_start = True
r_start = 0
r_end = 0
l_start = 0
l_end = 0

while r_start < len(s):
    r_end, l_start, l_end = get_ptr(s, r_start)
    r_cnt = r_end - r_start + 1
    l_cnt = l_end - l_start + 1
    num = (r_cnt + l_cnt) // 2
    if (r_cnt + l_cnt) % 2 == 0:
        ret[r_end] = num
        ret[l_start] = num
    elif r_cnt % 2 == 1:
        ret[r_end] = num + 1
        ret[l_start] = num
    else:
        ret[r_end] = num
        ret[l_start] = num + 1
    r_start = l_end + 1

print(*ret)


Measured memory_bytes: 6400
#include  <iostream>
#include  <stdio.h>
#include <algorithm>
#include <map>
#include <math.h>

using namespace std;
#include <vector>
#define rep(i,n) for (int i = 0; i < (n) ; i++)
#define INF 1e9
#define llINF 1e18
#define base10_4 10000      //1e4
#define base10_5 100000     //1e5
#define base10_6 1000000    //1e6
#define base10_7 10000000   //1e7
#define base10_8 100000000  //1e8
#define base10_9 1000000000 //1e9

#define MOD 1000000007
#define pb push_back
#define ll long long
#define ull unsigned long long
#define vint vector<int>
#define vll vector<ll>

//#include <stack>
//#include <queue>

string ans_Yes = "Yes"; 
string ans_No = "No"; 
string ans_yes = "yes"; 
string ans_no = "no"; 

ll A;
ll B;
ll C;
ll N;
ll M;
ll K;
vector<string> dic;

ll ltmp;
string stmp;
double dtmp;

/*
max 448,000,000
map<string,ll> count_map;
count_map['0']=0;
for(auto x : count_map) {
    string key = x.first;
    ll value = x.second;
}
*/

int main(){

    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    ll cntmax=1;
    map<string,ll> count_map;


    cin >> N;
    rep(ni,N){
        cin >> stmp;
        if(count_map.count(stmp)==0){
            count_map[stmp]=1;
        }else{
            count_map[stmp]++;
            if(count_map[stmp]>cntmax){
                cntmax = count_map[stmp];
            }
        }
    }

    for(auto cmi : count_map) {
        string key = cmi.first;
        ll value = cmi.second;
        if(value == cntmax){
            cout << key << endl;
        }
    }



    

}

Measured memory_bytes: 23936
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, s, e) for (int i = (int)(s); i <= (int)(e); i++)
#define printYesNo(is_ok) puts(is_ok ? "Yes" : "No");
#define printVector(v) rep(i, v.size()) cout << v[i] << endl;

int main()
{
  int N;
  cin >> N;
  vector<long long> a(3 * N);
  rep(i, 3 * N)
  {
    cin >> a[i];
  }

  priority_queue<long long, vector<long long>, greater<long long>> big;
  priority_queue<long long> small;

  vector<long long> big_sum(N + 1), small_sum(N + 1);

  rep(i, N)
  {
    big_sum[0] += a[i];
    big.push(a[i]);

    small_sum[0] += a[3 * N - 1 - i];
    small.push(a[3 * N - 1 - i]);
  }

  rep(i, N)
  {
    big.push(a[N + i]);
    big_sum[i + 1] = big_sum[i] + a[N + i] - big.top();
    big.pop();

    small.push(a[2 * N - 1 - i]);
    small_sum[i + 1] = small_sum[i] + a[2 * N - 1 - i] - small.top();
    small.pop();
  }

  reverse(small_sum.begin(), small_sum.end());
  long long ans = INT64_MIN;
  rep(i, N + 1)
  {
    ans = max(ans, big_sum[i] - small_sum[i]);
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 5996
using System;
using System.Linq;//リストの使用
using System.Collections.Generic;
using System.Text;//テキストの高速出力に必要
class Program
{
	static void Main()
	{
		long s = long.Parse(Console.ReadLine());
		bool[] answers = new bool[1000000];
    int answer = 2;

    answers[s] = true;
    
    while(true)
    {
      if(s % 2 == 0)
      {
        s /= 2;
      }else
      {
        s = 3*s+1;
      }

      if(answers[s]) break;
      else
      {
        answer++;
        answers[s] = true;
      }
    }
    
		Console.WriteLine(answer);
	}
}

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

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

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

    if(is_sorted(begin(p), end(p))){
        cout << "YES" << endl;
        return 0;
    }

    vector<int> t(N);
    for(int i = 0; i < N; ++i){
        for(int j = i+1; j < N; ++j){
            t = p;
            swap(t[i], t[j]);
            if(is_sorted(begin(t), end(t))){
                cout << "YES" << endl;
                return 0;
            }
        }
    }

    cout << "NO" << endl;
}

Measured memory_bytes: 256
import Data.Char
main = do
  xs <- map  digitToInt <$> getLine :: IO [Int]
  print $ sum $ dfs xs []
  
dfs :: [Int] -> [Int] -> [Int]
dfs [] ys = ys
dfs (x:xs) [] = dfs xs [x]
dfs (x:xs) (y:ys) =
  let
    t = dfs xs (x:y:ys)
    a = dfs xs ((x+10*y):ys) 
  in
    t ++ a

Measured memory_bytes: 892
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <stack>
#include <queue>
#include <complex>
#include <set>
#include <list>
#include <iomanip>
#include <map>
#include <functional>


using namespace std;
static const double EPS = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
#define rep(i,n) for(int i=0; i<n; ++i)
#define FOR(i,a,b) for(int i=a; i<=b; ++i)
#define FORR(i,a,b) for (int i=a; i>=b; --i)
#define all(c) (c).begin(), (c).end()
#define zero(a) memset(a,0,sizeof(a))
#define minus(a) memset(a,0xff,sizeof(a))
#define chmax(a,b) a=min((a),(b))
#define chmin(a,b) a=max((a),(b))


#define MOD 1000000007

typedef pair<int,int>P;
#define INF (1<<29)
 
struct edge { 
	int from, to; 
	edge (int from, int to){
		this->from=from; this->to=to;
	}
};
 
int V,E;
typedef vector<edge> edges;
vector<edges> G;

ll h, w, n;//
map<P,ll> m;//
ll ans[10];//
int main(){
	cin >> h >> w >> n;
	int a, b;
	rep(i, n) {
		cin >> a >> b; a--; b--;
		FOR(i, -1, 1) {
			FOR(j, -1, 1) {
				if ((a + i) >= 1 && (a + i) < (h - 1) && (b + j) >= 1 && (b + j) < (w - 1)) {
					m[P(a + i, b + j)]++;
				}
			}
		}
	}
	for (auto t : m) {
		ans[t.second]++;
	}
	ll tmp = 0;
	rep(i, 10) {
		tmp += ans[i];
	}
	ans[0] = (h - 2)*(w - 2) - tmp;
	rep(i, 10) {
		cout << ans[i] << endl;
	}
	return 0;
}


Measured memory_bytes: 56448
#include <cstdio>
#include <cmath>

#include <map>

#define incID(i, l, r) for(int i = (l)    ; i <  (r); i++)
#define incII(i, l, r) for(int i = (l)    ; i <= (r); i++)
#define decID(i, l, r) for(int i = (r) - 1; i >= (l); i--)
#define decII(i, l, r) for(int i = (r)    ; i >= (l); i--)
#define inc( i, n) incID(i, 0, n)
#define inc1(i, n) incII(i, 1, n)
#define dec( i, n) decID(i, 0, n)
#define dec1(i, n) decII(i, 1, n)

typedef long long   signed int LL;
typedef long long unsigned int LU;

template<typename T> void swap(T &x, T &y) { T t = x; x = y; y = t; return; }
template<typename T> T abs(T x) { return (0 <= x ? x : -x); }
template<typename T> T max(T a, T b) { return (b <= a ? a : b); }
template<typename T> T min(T a, T b) { return (a <= b ? a : b); }
template<typename T> bool setmin(T &a, T b) { if(a <= b) { return false; } else { a = b; return true; } }
template<typename T> bool setmax(T &a, T b) { if(b <= a) { return false; } else { a = b; return true; } }
template<typename T> T gcd(T a, T b) { return (b == 0 ? a : gcd(b, a % b)); }
template<typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; }

// ---- ----

int n, q, ans;
LL num[100001];
std::map<LL, LL> m; // pos, num

void ins(LL x, LL y) {
	auto result = m.insert(std::make_pair(x, y));
	if( ! result.second) {
		result.first -> second = y;
	}
}

int main() {
	scanf("%d%d", &n, &q);
	
	m.insert(std::make_pair(-1, 20000000000001LL));
	m.insert(std::make_pair(n, 0));
	inc(t, q) {
		int a;
		LL b;
		scanf("%d%lld", &a, &b);
		
		int ccc = 0;
		while(b > 0) {
			auto it2 = m.lower_bound(a - 1); 
			auto it = it2; it--;
			LL x = (it -> first);
			LL y = (it -> second);
			LL ny = (it2 -> second);
			LL d = a - 1 - x;
			LL s = d * (y - ny);
			
			if(b > s) {
				m.erase(x);
				ins(a - 1, y);
			} else {
				if(b > s - d) { m.erase(x); } ins((b - 1) % d + 1 + x, (b - 1) / d + 1 + ny);
				if(b > d && b % d != 0) { ins(a - 1, (b - 1) / d + ny); }
			}
			
			b -= s;
		}
	}
	
	auto it = m.begin();
	inc(i, n) {
		while(i > (it -> first)) { it++; }
		printf("%lld\n", it -> second);
	}
	
	return 0;
}


Measured memory_bytes: 7680
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define MOD 1000000007
#define ll long long int
#define pair <ll, ll> pi
#define vector <ll> vi
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define SQ(a) (a) * (a)
#define ordered_set tree<ll, null_type, greater_equal<ll>, rb_tree_tag, tree_order_statistics_node_update> //greater_equal<ll> or less<ll>
// find_by_key()   order_of_key()
//#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
/*bool comp(string a, string b) {
if (a.size() != b.size()) return a.size() < b.size();
return a < b;
}*/

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    //freopen('input.txt', 'r', stdin);
    //freopen('output.txt', 'w', stdout);
    ll i, j, k, n, m, b, d, t, ans = 0,a,x,y,c;
    cin>>a>>b>>c;
    if(a+b==c){
        cout<<"Yes"<<endl;
    }
    else if(a+c==b){
        cout<<"Yes"<<endl;
    }
    else if(b+c==a){
        cout<<"Yes"<<endl;
    }
    else{
        cout<<"No"<<endl;
    }
    return 0;
}

Measured memory_bytes: 3600
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
template<class t>
using table = vector<vector<t>>;

ld memo[1 << 16][16];
int M, N;
ld getans(const vector<vector<ld>>&ps,bitset<16>bs, const int now) {
	if (now == N)return 1;
	if (memo[bs.to_ulong()][now] > -0.5)return memo[bs.to_ulong()][now];
	ld ans = 0;
	for (int i = 0; i < M; ++i) {
		if (bs[i]) {
			bs[i] = false;
			ld live = 1;
			ld nans = 0;
			for (int op = now; op < N; ++op) {

				ld death = live*(1 - ps[i][op]);
				nans += death*getans(ps, bs, op);
				live -= death;
			}
			nans += live;
			ans = max(ans, nans);
			bs[i] = true;
		}
	}
	return memo[bs.to_ulong()][now] = ans;
}
int main() {
	for (int i = 0; i < 1 << 16; ++i) {
		for (int j = 0; j < 16; ++j) {
			memo[i][j] = -1;
		}
	}
	cin >> M >> N;

	vector<vector<ld>>ps(M, vector<ld>(N));
	for (int i = 0; i < M; ++i) {
		for (int j = 0; j < N; j++)
		{
			ld p; cin >> ps[i][j];
		}
	}
	ld ans = getans(ps, bitset<16>((1 << (M)) - 1), 0);
	cout << setprecision(22)<<fixed<<ans << endl;
	return 0;
}

Measured memory_bytes: 19684
#!/usr/bin/env python3

import sys
sys.setrecursionlimit(300000)

MOD = 998244353  # type: int
INV = pow(2, MOD - 2, MOD)

def calc_fraction_mod(numerator):
    '''
        returns numerator / denominator (mod MOD)
    '''
    #inv = pow(denominator, MOD - 2, MOD)
    return numerator * INV % MOD


def solve(N: int, S: int, A: "List[int]"):
    A.sort()
    dp = [0] * (S + 1)
    dp[0] = pow(2, N, MOD)
    for i, a in enumerate(A):
        for s in range(S + 1)[::-1]:
            if dp[s] == 0:
                continue
            if s + a <= S:
                dp[s + a] += calc_fraction_mod(dp[s])
                dp[s + a] %= MOD
    print(dp[S])

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    S = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, S, A)

if __name__ == '__main__':
    main()


Measured memory_bytes: 68504
class UF_tree:
    def __init__(self, n):
        self.root = [-1] * (n + 1)  # -1ならそのノードが根,で絶対値が木の要素数
        self.rank = [0] * (n + 1)

    def find(self, x):  # xの根となる要素番号を返す
        if self.root[x] < 0:
            return x
        else:
            self.root[x] = self.find(self.root[x])
            return self.root[x]

    def isSame(self, x, y):
        return self.find(x) == self.find(y)

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        elif self.rank[x] < self.rank[y]:
            self.root[y] += self.root[x]
            self.root[x] = y
        else:
            self.root[x] += self.root[y]
            self.root[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def getNodeLen(self, x):
        return -self.root[self.find(x)]


if __name__ == "__main__":
    n, m = map(int, input().split())
    p = tuple(map(int, input().split()))
    uf = UF_tree(n)
    for _ in range(m):
        x, y = map(int, input().split())
        uf.unite(x, y)

    ans = 0
    for i in range(n):
        if uf.isSame(p[i], i + 1):
            ans += 1
    print(ans)


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

using namespace std;

int N;

int main() {
	int a, b, s, f;

	cin >> a >> b >> N;
	for (int i = 0; i < N; ++i) {
		cin >> s >> f;
		if (a>=f || b<=s) {
			continue;
		}
		cout << "1" << endl;
		return 0;
	}
	cout << "0" << endl;
	
	return 0;
}


Measured memory_bytes: 3084
n = int(input())
h = list(map(int, input().split()))

dp = [0, abs(h[1]-h[0])]

for i in range(2, n):
    dp.append(min(dp[i-1] + abs(h[i]-h[i-1]), dp[i-2] + abs(h[i]-h[i-2])))

print(dp[-1])


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

void solve(long long N) {
    cout << (N*800) - ((N/15) * 200) << endl;
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);

  long long N;
  scanf("%lld", &N);
  solve(N);
  return 0;
}


Measured memory_bytes: 256
# -*- coding: utf-8 -*-
from collections import defaultdict
def primeFactors(n):
    res = []
    while n%2==0:
        res.append(2)
        n //= 2
    x = 3
    while n>1 and n>=x*x:
        while n%x==0:
            res.append(x)
            n //= x
        x += 2
    if n>1:
        res.append(n)
    return res

def modpow(a,n,m):
    res = 1
    while n>0:
        if n%2==1:
            res = (res * a) % m
        a = (a*a) % m
        n = n//2
    return res

MOD = 10**9 + 7
n = int(input())
d = defaultdict(int)
for i in range(1,n+1):
    for r in primeFactors(i):
        d[r] += 1

res = 1
for k in d.keys():
    res *= (d[k]+1)
    res %= MOD
print(res)

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

using ll = long long;
using P = pair<int, int>;
#define rep1(i,n) for (int i=1; i<=n; i++)
#define rep0(i,n) for (int i=0; i<n; i++)
#define zarray(x,n) x[n+1]; rep1(i,n) {x[i]=0;} 

int main() {
    int s, w;
    cin >> s >> w;
    string ans = "unsafe";
    if (s > w) {
        ans = "safe";
    }
    cout << ans << endl;
}


Measured memory_bytes: 3552
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

using ll = long long;

int main() {

    int n;
    cin >> n;

    vector<ll> v(n);

    for(int i = 0; i < n; ++i)
        cin >> v[i];

    sort(v.begin(), v.end(), greater<ll>());

    ll sum = v[0];

    int even = 0;
    int index = 1;
    
    for(int i = 1; i < n - 1; ++i) {

        sum += v[index];
        even++;
        if(even % 2 == 0) {
            even = 0;
            index++;
        }

    }


    cout << sum << endl;

    return 0;


}

Measured memory_bytes: 4784
extern crate core;

use std::str::FromStr;

struct Iostream {
    line: Vec<String>,
    position: usize
}
type Parse<T: FromStr> = Result<T, T::Err>;
impl Iostream {
    fn new() -> Iostream{
        Iostream {line:vec![], position: 0}
    }
    fn read_word(&mut self) -> &String {
        if self.position == self.line.len() {
            let mut line= String::new();
            std::io::stdin().read_line(&mut line).ok();
            self.line = line.split_whitespace().map(|x|x.to_string()).collect();
            self.position = 0
        }
        let result = &self.line[self.position];
        self.position += 1;
        result
    }
    fn read<T: FromStr>(&mut self) -> Parse<T> {
        self.read_word().parse()
    }
    fn get<T: FromStr>(&mut self) -> T {self.read().ok().unwrap()}
}
struct Sweets {
    id: i32,
    protein: i32,
    fat: i32,
    carbon: i32,
}
impl Sweets {
    fn calorie(&self) -> i32 {
        self.protein * 4 + self.carbon * 4 + self.fat * 9
    }
}
fn tabulate<T, F>(count: usize, elements: &mut F) -> Vec<T> where F: FnMut(usize) -> T {
    let mut result:Vec<T> = Vec::with_capacity(count);
    for i in 0 .. count {
        result.push(elements(i))
    }
    result
}
fn fill<T, F>(count: usize, generator: F) -> Vec<T> where F: Fn() -> T {
    let mut result: Vec<T> = Vec::with_capacity(count);
    for i in 0 .. count {
        result.push(generator())
    }
    result
}
fn main() {
    let mut stdin = Iostream::new();
    let input = &mut stdin;
    loop {
        let n: usize = input.get();
        if n == 0 {
            break
        }
        let sweets = tabulate(n, &mut |_idx| {
            let s: i32 = input.get();
            let p: i32 = input.get();
            let q: i32 = input.get();
            let r: i32 = input.get();
            Sweets { id: s, protein: p, fat: q, carbon: r }
        });
        let protein :i32 = input.get();
        let fat:i32 = input.get();
        let carbon:i32 = input.get();
        let calorie:i32 = input.get();
        let filtered: Vec<_> = sweets.iter().filter(|&x| x.calorie() <= calorie && x.protein <= protein && x.fat <= fat && x.carbon <= carbon).collect();
        if filtered.len() == 0 {
            println!("NA");
        } else {
            for s in filtered {
                println!("{}", s.id)
            }
        }
    }
}


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

int main(){
 
  ll N;cin>>N;
  int k; cin>>k;
  ll h[N], cost[N];
  int INF = 1e9 + 5;  
  for(ll i = 0; i < N; i ++) cin>>h[i];
  for(ll i = 0; i < N; i ++) cost[i] = INF;
  cost[0] = 0;
  cost[1] = abs(h[1]- h[0]);
  for(ll i = 2; i < N; i++){
  	for(ll j = 1; j <= k; j ++){
  		if(i - j >= 0){
  				cost[i] = min(cost[i], (cost[i - j] + abs(h[i] - h[i - j])));	
		  }	
	  }
  }
  cout<<cost[N - 1];
  return 0;
}

Measured memory_bytes: 1920
/*
    Author: Nguyen Tan Bao
    Status:
    Idea:
*/
 
#include <bits/stdc++.h>
#define FI first
#define SE second
#define EPS 1e-9
#define ALL(a) a.begin(),a.end()
#define SZ(a) int((a).size())
#define MS(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
//__builtin_ffs(x) return 1 + index of least significant 1-bit of x
//__builtin_clz(x) return number of leading zeros of x
//__builtin_ctz(x) return number of trailing zeros of x
 
using namespace std;
using ll = long long;
using ld = double;
typedef pair<int, int> II;
typedef pair<II, int> III;
typedef complex<ld> cd;
typedef vector<cd> vcd;
 
const ll MODBASE = 1000000007LL;
const int MAXN = 110;
const int MAXM = 1000;
const int MAXK = 16;
const int MAXQ = 200010;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    ll A, B, N;
    cin >> A >> B >> N;
    ll x = 0;
    if (N >= B) x = B - 1;
    else x = N;
    cout << (A * x) / B - A * (x / B);
    return 0;
}


Measured memory_bytes: 3640
// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	const inputLines = input.split("\n");
	const s = inputLines[0];
	const t = inputLines[1];

	var result = t.length;
	// if (s === t) {
	// 	return console.log(0);
	// }
	for (var i = 0; i < s.length - t.length+1; i++) {
		var current = 0;
		for (var j = 0; j < t.length; j++) {
			const a = s.substr(i + j, 1);
			const b = t.substr(j, 1);

			if (a !== b) {
				current += 1;
			}

			// console.log({
			// 	i: i,
			// 	j: j,
			// 	a: a,
			// 	b: b,
			// 	r: a !== b,
			// 	current: current,
			// 	result: result
			// });
		}
		if (current < result) {
			result = current;
		}
	}

	console.log(result);
	// tmp = input[1].split(" ");
	// //文字列から10進数に変換するときはparseIntを使います
	// var a = parseInt(input[0], 10);
	// var b = parseInt(tmp[0], 10);
	// var c = parseInt(tmp[1], 10);
	// var s = input[2];

	//出力
	// console.log('%d %s',a+b+c,s);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

// node index.js
// 1
// 2 3
// test
// (Ctrl + D)


Measured memory_bytes: 32484