akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <algorithm>
#include <numeric>
#include <vector>
#include <list>
#include <queue>
#include <string>
#include <map>
using namespace std;
#define lli long long int
#define MAX 1000000007

/*方針
*/
lli ans = 1;
int N;
string S;
string tmp;
map<char, int> mp;

void read()
{
    cin >> N >> S;
};
void solve()
{
    for (int cur = 0; cur < N; cur++)
    {
        mp[S[cur]]++;
    }
    for (auto &&i : mp)
    {
        ans *= (i.second + 1);
        ans = ans % MAX;
    }
    ans--;
};
int main()
{
    read();
    solve();
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 512
from collections import deque

N, Q = map(int, input().split())

eds = {i+1:[] for i in range(N)}

st = set([1])
rlt = [0]*(N+1)

for _ in range(N-1):
  a,b = map(int, input().split())
  eds[a].append(b)
  eds[b].append(a)
  
for _ in range(Q):
  q, x = map(int, input().split())
  rlt[q] += x

que = deque([1])

while len(que) > 0:
  p = que.popleft()
  for c in eds[p]:
    if c not in st:
      st.add(c)
      que.append(c)
      rlt[c] += rlt[p]

rlt = map(str, rlt[1:])
print(" ".join(rlt))

Measured memory_bytes: 145260
#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  int a = 0;
  int w = 0;
  int t = 0;
  int r = 0;
  for(int i=0;i<n;i++){
    string s;
    cin >> s;
    if(s == "AC"){
      a++;
    }else if(s == "WA") {
      w++;
    }else if(s == "TLE") {
      t++;
    }else r++;
  }
  cout << "AC" << " x " << a << endl;
  cout << "WA" << " x " << w << endl;
  cout << "TLE" << " x " << t << endl;
  cout << "RE" << " x " << r << endl;
}

Measured memory_bytes: 3616
/**
 *  author:   TakeruOkuyama
 *  created:  
**/
#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;

const int MOD = 1000000007;
const int INF = 999999999;

int main(){
    int N;
    string S;
    cin >> N >> S;
    vector<int> vE(N+1, 0), vW(N+1, 0);
    rep(i, N){
        vE[i+1] = vE[i];
        vW[i+1] = vW[i];
        if(S[i] == 'E'){
            vE[i+1]++;
        }else{
            vW[i+1]++;
        }
    }
    int ans = INF;

    rep(i, N){
        int now = vW[i] + (vE[N] - vE[i+1]);
        if(now < ans){
            ans = now;
        }
    }
    cout << ans << endl;
return 0;}

/**
 * g++ code.cpp
 * ./a.out
 * shift + ctrl + i
**/ 

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

int main(){
  int N, K;
  string S;
  cin >> N >> S >>K;
  //一文字ずつ比較していく
  for (int i=0; i<N; i++){
    //文字列SのK番目の文字と異なるかどうか判定する。
    if (S.at(i) == S.at(K-1)){
    }else{
      S.replace(i,1,"*");
    }
  }
  cout << S;
}


Measured memory_bytes: 256
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<functional>
#include<assert.h>
#include<numeric>
using namespace std;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
using ll = long long;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=998244353 ;
ll dp[202020][2];
string s;
ll rec(int k,int f,int m){
    if(k>=s.size()){
        return 1;
    }
    if(dp[k][f]!=-1)return dp[k][f];
    if(k<m){
        ll ret = 0;
        if(f){
            rep(j,2)ret+=rec(k+1,f,m);
        }
        else {
            if(s[k]=='1'){
                ret+=rec(k+1,f,m);
                ret+=rec(k+1,1,m);
            }
            else {
                ret+=rec(k+1,f,m);
            }
        }
        return dp[k][f]=ret%mod;
    }
    else {
        if(f==1)return 1;
        else {
            if(s[k-m]!=s[k])return dp[k][f]=rec(k+1,0,m);
            else {
                if(s[k]=='1')return dp[k][f]=1;
                else return dp[k][f]=0;
            }
        }
    }
}

int main(){
    int n;
    cin>>n;
    cin>>s;
    vector<ll> ans(n+1);
    REP(i,1,n+1){
        if(n%i==0&&(n/i)&1){
            rep(j,n+1)rep(k,2)dp[j][k]=-1;
            ans[i]=rec(0,0,i);
        }
    }
    for (int k = 1; k <=n ; ++k) {
    for (int i = k * 2; i <= n; i += k) {
      ans[i] += mod-ans[k];
      ans[i]%=mod;
    }
  }
  ll res=0;
  REP(i,1,n+1){
        if(n%i==0&&(n/i)&1){
            res+=2*i*ans[i]%mod;
        }
    }
    cout<<res%mod<<endl;
    return 0;
}


Measured memory_bytes: 17796
import math
def py():
    print("Yes")
def pn():
    print("No")
def iin():
    x = int(input())
    return x

neko = 0
nya = 0
nuko = 0

def che(a,b,c):
    if a%2:
        return 1
    elif b%2:
        return 1
    elif c%2:
        return 1
    else:
        return 0

a,b,c = map(int,input().split())
if(che(a,b,c)):
    print(0)
elif ((a == b)and(a == c)):
    print(-1)
else:
    while True:
        neko = neko + 1
        nya = a / 2
        nuko = b / 2
        a = c/2 + nuko
        b = c/2 + nya
        c = nuko + nya

        if a%2:
            break
        if b%2:
            break
        if c%2:
            break
    print(neko)

Measured memory_bytes: 3064
fn get_line() -> String {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string()
}

fn main() {
    let (x, _n) = {
        let ab = get_line()
            .split_whitespace()
            .map(|e| e.parse().unwrap())
            .collect::<Vec<isize>>();
        (ab[0], ab[1])
    };

    let mut ps = get_line()
        .split_whitespace()
        .map(|e| e.parse().unwrap())
        .collect::<Vec<isize>>();
    ps.sort();

    if ps.len() == 0 {
        println!("{}", x);
        return;
    }

    let (max, min) = (ps.iter().max().unwrap(), ps.iter().min().unwrap());

    if x < *min || *max < x {
        println!("{}", x);
        return;
    }
    let v: Vec<isize> = (*min..=*max).filter(|x| !ps.contains(x)).collect();

    let mut minimum = 100000000;
    let mut current = *min;

    for i in &v {
        if (x - i).abs() < minimum {
            minimum = x - i;
            current = *i;
        }
    }

    if current == *min {
        if (x - (min - 1)).abs() > (x - (max + 1)).abs() {
            println!("{}", max + 1);
        } else {
            println!("{}", min - 1);
        }
    } else {
        println!("{}", current);
    }
}


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

int gcd(int a, int b)
{
	while(b != 0){
		a %= b;
		if(a == 0) return b;
		b %= a;
	}
	return a;
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);  
	
	int n; cin >> n;
	int x; cin >> x;
	vector<int> dist(n);
	for(int i = 0; i < n; i++) {
		int tmp; cin >> tmp;
		dist[i] = abs(tmp - x);
	}
	int ans = dist[0];
	for(int i = 1; i < n; i++){
		ans = gcd(ans, dist[i]);
	}
	cout << ans << endl;
	return 0;	
}


Measured memory_bytes: 640
def is_wide(t1, t2):
	if t1 == t2:
		return True
	return False

n = int(input())
t1 = input()
#t2 = list(input().split())

ans = 1
pos = 0
while pos < len(t1):
	if pos == 0:
		w = 6
		l = 3
	else:
		if prev_wide:
			w = 3
			l = 1
		else:
			w = 2
			l = 2
	prev_wide = False
	if len(t1) > pos+1:
		if is_wide(t1[pos], t1[pos+1]):
			ans *= w
			pos += 1
			prev_wide = True
		else:
			ans *= l
	else:
		ans *= l
	ans %= 1000000007
	pos += 1
print(ans)


Measured memory_bytes: 3188
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] p = new int[n];
        int[] min_p = new int[n];
        int counter = 0;
        for (int i = 0; i < p.length; i++) {
            p[i] = sc.nextInt();
        }
        min_p[0] = p[0];
        for (int i = 0; i < n; i++) {
            if (i >= 1) {
                if (min_p[i - 1] > p[i]) {
                    min_p[i] = p[i];
                } else {
                    min_p[i] = min_p[i - 1];
                }
            }
            if (p[i] == min_p[i]) {
                counter++;
            }
        }
        System.out.println(counter);
        sc.close();
    }
}

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


int main() {
	int N,X,Y;
	cin>>N>>X>>Y;
	vector<int> p(N);
	
	for(int i=1;i<=N-1;i++){
		for(int j=i+1;j<=N;j++){
			int k=min(j-i,abs(X-i)+1+abs(Y-j));
			p[k]++;
		}
	}
	
	for(int i=1;i<N;i++)cout<<p[i]<<endl;
}


Measured memory_bytes: 256
# https://atcoder.jp/contests/abc138/tasks/abc138_d

import sys
input = sys.stdin.readline
import marshal


class Graph:
    def __init__(self, n, dictated=False, decrement=True, destroy=False, edge=[]):
        self.n = n
        self.dictated = dictated
        self.decrement = decrement
        self.destroy = destroy
        self.edge = [set() for _ in range(self.n)]
        self.parent = [-1]*self.n
        self.info = [-1]*self.n
        for x, y in edge:
            self.add_edge(x,y)

    def add_edge(self, x, y):
        if self.decrement:
            x -= 1
            y -= 1
        self.edge[x].add(y)
        if self.dictated == False:
            self.edge[y].add(x)

    def add_adjacent_list(self, i, adjacent_list):
        if self.decrement:
            self.edge[i] = set(map(lambda x:x-1, adjacent_list))
        else:
            self.edge[i] = set(adjacent_list)

    def dfs2(self, info, start, goal=-1, time=0, save=False):
        """
        :param info: 各頂点の付加情報
        :param start: スタート地点
        :param goal: ゴール地点
        :param save: True = 前回の探索結果を保持する
        :return: ゴール地点までの距離。存在しなければ -1
        """

        if self.decrement:
            start -= 1
            goal -= 1
        if not save:
            self.parent = [-1] * self.n
        if self.destroy:
            edge2 = self.edge
        else:
            edge2 = marshal.loads(marshal.dumps(self.edge))

        p, t = start, time
        self.parent[p] = -2
        while True:
            if edge2[p]:
                q = edge2[p].pop()
                if q == self.parent[p] and not self.dictated:
                    """ 逆流した時の処理 """
                    """"""""""""""""""""
                    continue
                if self.parent[q] != -1:
                    """ サイクルで同一点を訪れた時の処理 """
                    """"""""""""""""""""
                    continue
                if q == goal:
                    """ ゴール時の処理"""
                    # return t + 1
                    """"""""""""""""""""
                    continue
                """ p から q への引継ぎ"""
                info[q] += info[p]
                """"""""""""""""""""
                self.parent[q] = p
                p, t = q, t + 1
            else:
                """ 探索完了時の処理 """
                """"""""""""""""""""
                if p == start and t == time:
                    break
                p, t = self.parent[p], t-1
                """ 二度目に訪問時の処理 """

                """"""""""""""""""""
        return info


######################################################################################################

N, Q = map(int, input().split())  # N:頂点数, Q: クエリの数
M = N-1

graph = Graph(N, dictated=False, destroy=True)

for _ in range(M):
    x, y = map(int, input().split())
    graph.add_edge(x,y)

info = [0] * N
for _ in range(Q):
    p, x = map(int, input().split())
    info[p - 1] += x

print(*graph.dfs2(info, start=1))



Measured memory_bytes: 166644
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
template<typename T> void chkmax(T &a, const T &b) { a = a > b ? a : b; }
template<typename T> void chkmin(T &a, const T &b) { a = a < b ? a : b; }

const int MAXN = 305;
char S[MAXN];
int f[2][MAXN][MAXN], n, K;

int main() {
	scanf("%s%d", S + 1, &K);
	n = strlen(S + 1);
	memset(f[1], 0xc0, sizeof(f[1]));
	for (int i = 0; i <= K; i++) {
		int a = i & 1, b = !a;
		for (int j = n; j > 0; j--) {
			f[a][j][j] = 1;
			for (int k = j + 1; k <= n; k++) {
				chkmax(f[a][j][k], max(f[a][j + 1][k], f[a][j][k - 1]));
				chkmax(f[a][j][k], max(f[b][j][k], f[S[j] == S[k] ? a : b][j + 1][k - 1] + 2));
			}
		}
	}
	printf("%d\n", f[K & 1][1][n]);
	return 0;
}

Measured memory_bytes: 1024
import java.util.Scanner;


public class Main {
	String s = "";
	char a;
	boolean flag;
	int count = 0;

	public static void main(String args[]){
		new Main().run();
	}

	void run(){
		Scanner sc = new Scanner(System.in);
		//need loop
		//need loop
		while(true){
			s = sc.next();
			a = s.charAt(0);
			count = 0;
			if(a == '#')break;
			if(a == 'q' || a == 'w' || 
					a == 'e' || a == 'r' || a == 't' || a == 'a' ||
					a == 's' || a == 'd' || a == 'f' || a == 'g' ||
					a == 'z' || a == 'x' || a == 'c' || a == 'v' || a == 'b'){
				flag = true;
			}
			if(a == 'y' || a == 'u' || 
					a == 'i' || a == 'o' || a == 'p' || a == 'h' ||
					a == 'j' || a == 'k' || a == 'l' || a == 'n' ||
					a == 'm'){
				flag = false;
			}
			for(int i = 1; i < s.length(); i++){
				a = s.charAt(i);
				if(a == 'q' || a == 'w' || 
						a == 'e' || a == 'r' || a == 't' || a == 'a' ||
						a == 's' || a == 'd' || a == 'f' || a == 'g' ||
						a == 'z' || a == 'x' || a == 'c' || a == 'v' || a == 'b'){
					if(flag == false){
						count++;
						flag = true;
					}
				}
				if(a == 'y' || a == 'u' || 
						a == 'i' || a == 'o' || a == 'p' || a == 'h' ||
						a == 'j' || a == 'k' || a == 'l' || a == 'n' ||
						a == 'm'){
					if(flag == true){
						count++;
						flag = false;
					}
				}
			}
			System.out.println(count);
		}
		
	}
}

Measured memory_bytes: 19928
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

	public static void main(String[] args) {
		FastScanner fs = new FastScanner();
	     int l =fs.nextInt();
	     int r=fs.nextInt();
	     int d=fs.nextInt();
	     int count=0;
	     for(int i=l;i<=r;i++) {
	    	 if(i%d==0) count++;
	    	
	    	
	     }
	     System.out.println(count);
	    	
	     
	    	 }

	static void sort(int[] a ) {
		ArrayList<Integer> l = new ArrayList<>();
		for(int i:a) l.add(i);
		Collections.sort(l);
		for(int i=0;i<l.size();i++) a[i]=l.get(i);
	}
	static class FastScanner {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer("");
		String next() {
			while(!st.hasMoreTokens())
				try {
					st = new StringTokenizer(br.readLine());
				}catch(IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a = new int[n];
			for(int i=0;i<n;i++)a[i]=nextInt();
			return a;
		}
		long nextLong() {
			return Long.parseLong(next());
		}
	}

}


Measured memory_bytes: 32572
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>

using namespace std;

#if defined(_MSC_VER)
#pragma warning(disable: 4996)  // VSでscanfを使う．
#endif

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

  if ((n + 1) / 2 < k) {
    cout << "NO" << endl;
  } else {
    cout << "YES" << endl;
  }


  return 0;
}

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

using namespace std;

int main() {
  int a,b,c;
  cin>>a>>b>>c;
  int arr[11];
  memset(arr, 0, 11);
  arr[a]++; arr[b]++; arr[c]++;
  if(arr[5] == 2 && arr[7] == 1) cout<<"YES";
  else cout<<"NO";
  return 0;
}

Measured memory_bytes: 256
import sys
def input(): return sys.stdin.readline().rstrip()
series = [1, 1, 1, 2, 1, 2, 1, 5, 
          2, 2, 1, 5, 1, 2, 1, 14, 
          1, 5, 1, 5, 2, 2, 1, 15, 
          2, 2, 5, 4, 1, 4, 1, 51]

print(series[int(input())-1])

Measured memory_bytes: 3060
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <cctype>
#include <cassert>
#include <climits>
#include <string>
#include <bitset>
#include <cfloat>
#include <unordered_set>
#pragma GCC optimize("Ofast")
using namespace std;
typedef long double ld;
typedef long long int ll;
typedef unsigned long long int ull;
typedef vector<int> vi;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<double> vd;
typedef vector<string> vs;
typedef vector<ll> vll;
typedef vector<pair<int,int> > vpii;
typedef vector<vector<int> > vvi;
typedef vector<vector<char> > vvc;
typedef vector<vector<string> > vvs;
typedef vector<vector<ll> > vvll;
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define irep(it, stl) for(auto it = stl.begin(); it != stl.end(); it++)
#define drep(i,n) for(int i = (n) - 1; i >= 0; --i)
#define fin(ans) cout << (ans) << '\n'
#define STI(s) atoi(s.c_str())
#define mp(p,q) make_pair(p, q)
#define pb(n) push_back(n)
#define all(a) a.begin(), a.end()
#define rall(a) a.rbegin(), a.rend()
#define Sort(a) sort(a.begin(), a.end())
#define Rort(a) sort(a.rbegin(), a.rend())
#define MATHPI acos(-1)
#define itn int;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
template <class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;} return 0;}
template <class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;} return 0;}
struct io{io(){ios::sync_with_stdio(false);cin.tie(0);}};
const int INF = INT_MAX;
const ll LLINF = 1LL<<60;
const ll MOD = 1000000007;
const double EPS = 1e-9;



int main(void) {

    
    ll n;
    cin>>n;
    vvll v(n,vll(10));
    rep(i,n)rep(j,10)cin>>v[i][j];
    vvll p(n,vll(11));
    rep(i,n)rep(j,11)cin>>p[i][j];
    ll ans=-LLINF;
    for(ll i=1;i<(1<<10);i++){
        vll open(10,0);
        ll t=i;
		ll pos=0;
		while(t>0){
			open[pos]=t%2;
			t/=2;
			pos++;
		}
        ll tmp=0;
        for(ll j=0;j<n;j++){
            ll itti=0;
            rep(k,10){
                if(v[j][k]==open[k]&&open[k]==1){
                    itti++;
                }
            }
            tmp+=p[j][itti];
        }
        chmax(ans,tmp);
    }
    fin(ans);
}

Measured memory_bytes: 256
from math import floor, sqrt
from collections import defaultdict
N,M = map(int,input().split())
d = defaultdict(int)
for i in range(2, floor(sqrt(M))+1):
    while M % i == 0:
        d[i] += 1
        M //= i
if M != 1:
    d[M] += 1
def comb(n,k):
    if k == 0:
        return 1
    return comb(n-1,k-1) * n // k
ans = 1
for e in d.values():
    ans *= comb(N+e-1, e)
print(ans % (10**9+7))

Measured memory_bytes: 9336
#-*-coding:utf-8-*-

def main():
    given = ["dreamer", "dream", "eraser", "erase"]
    S = input()
    judge = [S.endswith(i) for i in given]
    while len(S) > 0:
        judge = [S.endswith(i) for i in given]
        if any(judge):
            target = given[judge.index(True)]
            S = S[:-len(target)]
            if len(S) == 0:
                print("YES")
                break
        else:
            print("NO")
            break
            
            




if __name__ == '__main__':
    main()
    

Measured memory_bytes: 3188
import sys
from collections import deque

H, W = map(int, sys.stdin.readline().split())
cy, cx = map(int, sys.stdin.readline().split())
gy, gx = map(int, sys.stdin.readline().split())
cy -= 1
cx -= 1
gy -= 1
gx -= 1
grid = []
for _ in range(H):
    grid.append(sys.stdin.readline().strip())
q = deque()
q.append((cx, cy, 0))
visited_d = {}
visited_e = {}
ans = float("inf")
while q:
    x, y, e = q.popleft()
    if (x, y) in visited_e and visited_e[(x, y)] <= e:
        continue
    visited_e[(x, y)] = e
    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        nx = x + dx
        ny = y + dy
        if 0 <= nx < W and 0 <= ny < H and grid[ny][nx] != "#":
            if nx == gx and ny == gy:
                ans = min(ans, e)
                continue
            if (nx, ny) not in visited_e:
                q.appendleft((nx, ny, e))
    for dx in range(-2, 3):
        for dy in range(-2, 3):
            if abs(dx) == 1 and dy == 0 or abs(dy) == 1 and dx == 0:
                continue
            nx = x + dx
            ny = y + dy
            if 0 <= nx < W and 0 <= ny < H and grid[ny][nx] != "#":
                if nx == gx and ny == gy:
                    ans = min(ans, e + 1)
                    continue
                if (nx, ny) not in visited_e:
                    q.append((nx, ny, e + 1))
print(-1 if ans == float("inf") else ans)


Measured memory_bytes: 236740
#include<bits/stdc++.h>
using namespace std;
const int mo=1e9+7;
inline int poww(int x,int y){int ans=1;for(;y;y>>=1,x=1ll*x*x%mo)if(y&1)ans=1ll*ans*x%mo;return ans;}
int H,W,T,x,g1,g2,g3,g4;
int main(){
	scanf("%d%d%d",&H,&W,&T);
	g4=__gcd(__gcd(H,W),T);H/=g4;W/=g4;T/=g4;
	g1=__gcd(H,W);g2=__gcd(H,T);g3=__gcd(W,T);
	printf("%d\n",poww((1ll*poww(2,g1)+poww(2,H/g2)+poww(2,W/g3)+mo-3)%mo,1ll*g2*g3*g4*g4%(mo-1)));
}

Measured memory_bytes: 256
/*I MAY NOT GET THE SUCCESS IMMEDIATELY BUT I WILL GET IT FOR SURE*/
#include<bits/stdc++.h>
#define opt std::ios_base::sync_with_stdio(false)
#define I int
#define li      int32_t
#define lli     long long
#define ulli unsigned long long

#define pn           printf("\n")
#define nl           cout<<'\n'
#define sf(N)        scanf("%lld",&N)
#define pf(N)        printf("%lld",N)
#define sf1(N1,N2)    scanf("%lld %lld",&N1,&N2)
#define pf1(N1,N2)    printf("%lld %lld",N1,N2)
#define sf2(N1,N2,N3) scanf("%lld %lld %lld",&N1,&N2,&N3)
#define pf2(N1,N2,N3) printf("%lld %lld %lld",N1,N2,N3)

#define sl          cout<<' '
#define ps          printf(" ")

#define rep(i,a,b)  for(i=a;i<b;i++)
#define repr(i,a,b) for(i=a;i>b;i--)
#define elif        else if
#define mset(a,b)   memset(a,b,sizeof(a))

#define pb      push_back
#define pob     pop_back
#define itr     iterator
#define sz()    size()
#define szof    sizeof
#define lb      lower_bound
#define ub      upper_bound
#define mp      make_pair
#define vlli    vector<lli>
#define plli    pair<lli,lli>
#define vplli   vector<plli >
#define F       first
#define S       second
#define Dup     erase(unique(V.begin(),V.end()),V.end())

#define bs      binary_search
#define ub      upper_bound
#define lb      lower_bound

#define ALL(V)  V.begin(),V.end()

#define MX1     100000
#define MX2     1000000
#define mod     1000000007
#define Inf     1000000000000000
using namespace std;

lli dp[3*MX1+1];
lli dp1[3*MX1+1];

lli Power(lli a,lli b)
{
    lli result=1;

    while(b)
    {
        if(b%2)
        {
            result=(result*a)%mod;
        }

        b=b>>1;
        a=(a*a)%mod;
    }

 return result;
}

int main()
{
    /*#ifndef ONLINE_JUDGE
    freopen("double_squares.txt","r",stdin);
    freopen("double_squares_out.txt","w",stdout);
    #endif // ONLINE_JUDGE*/

    lli N,i;
    cin>>N;

    vlli V;
    V.pb(0);
    rep(i,0,3*N)
    {
        lli x;
        cin>>x;

        V.pb(x);
    }

    multiset<lli>M;
    multiset<lli>:: itr it;

    lli Sum=0;
    rep(i,1,N+1)
    {
        M.insert(V[i]);
        Sum+=V[i];
    }

    dp[N]=Sum;

    rep(i,N+1,2*N+1)
    {
        M.insert(V[i]);
        Sum+=V[i]-*M.begin();
        M.erase(M.begin());

        dp[i]=Sum;
    }

    M.clear();

    Sum=0;
    repr(i,3*N,2*N)
    {
        M.insert(-V[i]);
        Sum+=V[i];
    }

    dp1[2*N+1]=Sum;

    repr(i,2*N,N)
    {
        M.insert(-V[i]);
        Sum+=V[i]+*M.begin();
        M.erase(M.begin());

        dp1[i]=Sum;
    }

    lli Max=-Inf;
    rep(i,N,2*N+1)
    {
        Max=max(Max,dp[i]-dp1[i+1]);
    }

    cout<<Max;




 return 0;
}


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

int main() {
  int A ,B ,N;//Aが時間で変わるの方、Bが固定の方、Nが止まった時間
  cin >> N >> A >> B;
  int payA = A * N;
  if (payA > B) cout << B << endl;
  else cout << payA << endl;
}

Measured memory_bytes: 384
#include<algorithm>
#include<iostream>
#include<string>
#include<cstdlib>
#include<cstring>
#include<cmath>
using namespace std;
int main(){
  int i,j,k,l;
  int n;
  while(cin>>n&&n){
    int w,h;
    cin>>w>>h;
    int a[200][200];
    memset(a,0,sizeof(a));
    for(i=0;i<n;i++){
      int x,y;
      cin>>x>>y;
      x--;
      y--;
      a[x][y]=1;
    }
    int s,t;
    cin>>s>>t;
    int mx=0;
    for(i=0;i<h;i++){
      for(j=0;j<w;j++){
	int ct=0;
	for(k=0;k<t;k++){
	  for(l=0;l<s;l++){
	    if(a[j+l][i+k])
	      ct++;
	  }
	}
	mx=max(mx,ct);
      }
    }
    cout<<mx<<endl;
  }
  return 0;
}

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

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

    vector<int> v(n);
    for(int i; i < n; i++){
        cin >> v.at(i);
    }
    sort(v.begin(),v.end());

    int cnt = 1;
    for(int i; i < n - 1; i++){
        if(v.at(i) == v.at(i+1)){
        }else{
            cnt++;
        }
    }
    cout << cnt << endl;
}

Measured memory_bytes: 256
void main(){
	string n = readln().chomp();
	writeln(n.count('9')==0? "No": "Yes");
}

import std.stdio, std.conv, std.algorithm, std.numeric, std.string, std.math;

// 1要素のみの入力
T _scan(T= int)(){
	return to!(T)( readln().chomp() );
}

// 1行に同一型の複数入力
T[] _scanln(T = int)(){
	T[] ln;
	foreach(string elm; readln().chomp().split()){
		ln ~= elm.to!T();
	}
	return ln;
}


Measured memory_bytes: 2632
import sys
import math
from collections import defaultdict
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def main():
    N, X, M = NMI()
    A = []
    A_ID = {}
    break_flag = False
    start = 0
    end = N
    for i in range(M):
        if i == 0:
            A.append(X)
            A_ID[X] = 0
        else:
            x = A[-1]**2 % M
            if x not in A_ID:
                A.append(x)
                A_ID[x] = i
            else:
                A.append(x)
                start = A_ID[x]
                end = i
                break_flag = True
            if break_flag:
                break

    if N < start+1:
        print(sum(A[:N]))
        exit()

    ans = sum(A[:start])
    lp = sum(A[start:end])
    gap = end - start
    lp_n = (N - start) // gap
    rem = (N - start) % gap
    ans += lp * lp_n + sum(A[start: start + rem])
    print(ans)




if __name__ == "__main__":
    main()

Measured memory_bytes: 16380
//#include <ext/pb_ds/assoc_container.hpp>
#include <bits/stdc++.h>
using namespace std;
// using namespace __gnu_pbds;
// template <class c, class cmp = less<c> > using ordered_set = tree<c, null_type, cmp, rb_tree_tag, tree_order_statistics_node_update>;
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL); 

#define ld long double


#define TRACE
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...) 1
#endif
template<class T> ostream& operator<<(ostream &os, vector<T> V) {os << "[ "; for(auto v : V) os << v << " "; return os << "]";}
template<class L, class R> ostream& operator<<(ostream &os, pair<L,R> P) {return os << "(" << P.first << "," << P.second << ")";}
template <typename T,typename U>pair<T,U> operator+(const pair<T,U> & l,const std::pair<T,U> & r) { return {l.first+r.first,l.second+r.second};}

typedef long long int ll;
#define int ll
#define endl '\n'
const ll mod =1e9+7;
const ll MAX_NODES =200001;
const ll MAX_LOG =50;
const ll inf = 1e18+123;
const int maxn = 200001;
int vis[101];
int32_t main()
{

   IOS
    int n,a[3];
    vector<char> v;
    cin>>n>>a[0]>>a[1]>>a[2];
    vector<string> all;
    for(int i = 1;i<=n;i++){
      string s;
      cin>>s;
      all.push_back(s);
    }
    
    for(int i  = 0;i<n;i++){
      string s = all[i];
      s[0]-='A';
      s[1] -= 'A';
      if(a[s[0]] == 0 and a[s[1]] == 0){
        cout<<"No"<<endl;
        return 0;
      }
      if(a[s[0]] == 1 and a[s[1]] == 1 and i<n-1){
        string t =  all[i+1];
        t[0]-='A';
        t[1]-='A';
        int l = 3-t[0]-t[1];
        if(l == s[0]){
          swap(s[0],s[1]);
        }
      }
      
      if(a[s[0]]>a[s[1]])
        swap(s[0],s[1]);
      a[s[0]]++;
      a[s[1]]--;
      
      v.push_back(char(s[0]+'A'));
    }
    cout<<"Yes"<<endl;
    for(int i = 0;i<n;i++){
      cout<<v[i]<<endl;
    }
} 


Measured memory_bytes: 7412
// キュー
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<limits.h>

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<vector>

//const int MAX_N = 100000;
const int STR_LEN = 10;

// キュー関連の定義
const int Max_Queue = 100000;

// キューの要素の構造体
typedef struct q_e
{
    // 配列の要素No.
    int id;
    // プロセス名
    char process_name[STR_LEN];
    // プロセスの時間
    int process_time;
}queue_element;

queue_element ary_queue[Max_Queue];

// キューの情報の構造体
typedef struct q_i
{
    int head;
    int tail;
    int count;
}queue_info;

queue_info que_info;

void create_queue(void);
int enqueue(queue_element element);
queue_element dequeue(void);

int main(void)
{

    int N, cpu_time, total_time = 0;
    char str[STR_LEN];
    queue_element que_ele;

    // キューの初期化
    create_queue();

    scanf("%d %d", &N, &cpu_time);

    for(int i = 0; i < N; i++)
    {
    	que_ele.id = i;

        scanf("%s", &str[0]);
        strcpy(&(que_ele.process_name[0]), &str[0]);

        scanf("%s", &str[0]);
        que_ele.process_time = atoi(str);

        // キューに挿入する
        enqueue(que_ele);
    }

    // cpuの時間を割り当てる
    while( que_info.count > 0 )
    {
        // キューからポップする
        que_ele = dequeue();

        if( 0 < que_ele.process_time
            && que_ele.process_time <= cpu_time )
        {
            total_time += que_ele.process_time;
            que_ele.process_time = 0;

            printf("%s %d\n", que_ele.process_name, total_time);
        }
        else
        {
            total_time += cpu_time;
            que_ele.process_time -= cpu_time;

            enqueue(que_ele);
        }
    }

    return 0;

}

// キューを作成する関数
void create_queue(void)
{
    int i;

    for(i = 0; i < Max_Queue; i++)
    {
        // キューの初期化
    	ary_queue[i].id = 0;
        ary_queue[i].process_name[0] = '\0';
        ary_queue[i].process_time = 0;
    }

    que_info.head = 0;
    que_info.tail = 0;
    que_info.count = 0;

    return;
}

// キューへプッシュする関数
int enqueue(queue_element element)
{

    if( que_info.count > Max_Queue )
    {
        // サイズオーバー
        return INT_MIN;
    }

    if( que_info.tail == Max_Queue - 1 )
    {
        // 配列をラウンド型にする
        que_info.tail = -1;
    }

    // キューに追加する
    ary_queue[que_info.tail++] = element;
    que_info.count++;

    return 0;
}

// キューからポップする関数
queue_element dequeue(void)
{
    queue_element ret;

    if( que_info.count < 0 )
    {
        // キューが空の時
        ret.id = INT_MIN;
    }
    else
    {
        if( que_info.head == Max_Queue - 1 )
        {
            // 配列をラウンド型にする
            que_info.head = -1;
        }

        // キューから取り出す
        ret = ary_queue[que_info.head++];
    }

    que_info.count--;

    return ret;
}



Measured memory_bytes: 5168
class RollingHash():
    def __init__(self,s):
        self.n=n=len(s)
        self.b=b=129
        self.M=M=2**61-1
        x,y=1,0
        self.f=f=[x]*(n+1)
        self.h=h=[y]*(n+1)
        for i,c in enumerate(s.encode()):
            f[i+1]=x=x*b%M
            h[i+1]=y=(y*b+c)%M
    def get(self,l,r):
        return(self.h[r]-self.h[l]*self.f[r-l])%self.M
def check(x):
    d={}
    for i in range(0,n-x+1):
        k=s.get(i,i+x)
        if k in d:
            if d[k]+x<=i:
                return True
        else:
            d[k]=i
    return False
n=int(input())
s=RollingHash(input())
ok,ng=0,n
while ng-ok>1:
    mid=ok+ng>>1
    if check(mid):
        ok=mid
    else:
        ng=mid
print(ok)

Measured memory_bytes: 44528
import sys


def main():
    input_str = sys.stdin.readline()
    a, b = [int(i) for i in input_str.split(' ')]
    if a > b:
        print('a > b')
    elif a < b:
        print('a < b')
    else:
        print('a == b')

    return


if __name__ == '__main__':
    main()



Measured memory_bytes: 5600
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <string>
#include <queue>
#include <set>

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

int main() {
    ll N, S;
    cin >> N >> S;
    ll A[N];
    REP(i, N) cin >> A[i];

    ll dp[N + 1][S + 1] = {};
    dp[0][0] = 1;
    REP(i, N) REP(j, S + 1) {
        dp[i + 1][j] += 2 * dp[i][j];
        dp[i + 1][j] %= MOD;

        ll sum = j + A[i];
        if (sum > S) continue;
        dp[i + 1][sum] += dp[i][j];
        dp[i + 1][sum] %= MOD;
    }
    cout << dp[N][S] << endl;
    return 0;
}

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

int main(void){
    // Your code here!
    int N;
    cin >> N;
    
    int A[25];
    int B[25];
    int C[25];
    
    for(int i = 0; i < N; i++) cin >> A[i];
    for(int i = 0; i < N; i++) cin >> B[i];
    for(int i = 0; i < N-1; i++) cin >> C[i];
    
    int sum = 0;
    for(int i = 0; i < N; i++){
        sum += B[i];
    }
    
    for(int i = 0; i < N-1; i++){
        if(A[i+1] - A[i] == 1){
            sum += C[A[i]-1];
        }
    }
    
    cout << sum << endl;
    
}


Measured memory_bytes: 256
open Batteries
open BatPrintf

let scan fmt f =
  BatScanf.sscanf (read_line ()) fmt f

let scan_list cnv =
  read_line ()
  |> BatString.split_on_char ' '
  |> List.map cnv

let rec zip xs ys =
  match xs, ys with
  | [], _ -> []
  | _, [] -> []
  | x::xs, y::ys ->
    (x, y) :: zip xs ys

let (a,b,c)= scan "%d %d %d" @@ BatTuple.Tuple3.make

let () =
  (if (a != b &&  b != c && c != a) || ( a == b && b == c && c == a) then
     "No"
   else
     "Yes")
  |> printf "%s\n"


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

int main() {
    int n;
    cin >> n;
    long long int A[3*n];
    for(int i = 0; i < 3*n; i++){
        cin >> A[i];
    }
    sort(A, A+3*n);
    long long int count = 0;
    for(int k = 1; k <= n; k++){
        count += A[3*n - 2*k];
    }
    cout << count << endl;
    return 0;
}




Measured memory_bytes: 2560
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <set>
#include <queue>
#include <map>
using namespace std;
typedef long long int ll;

int main(){
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	int n; cin >> n;
	vector<int> a(n);
	for(int i=0;i<n;i++){
		int x; cin >> x;
		a[x-1]++;
	}
	sort(a.begin(),a.end());
	vector<int> s(n+1);
	for(int i=0;i<n;i++){
		s[i+1]=s[i]+a[i];
	}
	for(int k=1;k<=n;k++){
		int l=0,r=n/k+1;
		while(r-l>1){
			int mid=(l+r)/2;
			bool ok=[&](int mid){
				int i=lower_bound(a.begin(),a.end(),mid)-a.begin();
				int sum=mid*(n-i)+s[i];
				return (sum>=mid*k);
			}(mid);
			if(ok){
				l=mid;
			}
			else{
				r=mid;
			}
		}
		cout << l << endl;
	}
}

Measured memory_bytes: 3200
using System;

public class hello
{
    public static int n;
    public static int[] a;
    public static void Main()
    {
        string[] line = Console.ReadLine().Trim().Split(' ');
        n = int.Parse(line[0]);
        var q = int.Parse(line[1]);
        line = Console.ReadLine().Trim().Split(' ');
        a = Array.ConvertAll(line, int.Parse);
        line = Console.ReadLine().Trim().Split(' ');
        for (int i = 0; i < q; i++)
            getAns(long.Parse(line[i]));
    }
    static void getAns(long x)
    {
        var ans = 0L;
        var s = 0L;
        var j = 0;
        for (int i = 0; i < n; i++)
        {
            while (j < n && s + a[j] <= x)
            {
                s += a[j];
                j++;
            }
            ans += j - i;
            s -= a[i];
        }
        Console.WriteLine(ans);
    }
}



Measured memory_bytes: 23044
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define forn(i, n) for (int i = 0; i < int(n); i++)
#define in insert
#define all(x) (x).begin(), (x).end()
#define speed ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int INF = 1e9 + 5;
int main(){
    int n;
    cin >> n;
    map<int, int> m;
    forn(i, n){
        int x;
        cin >> x;
        m[x]++;
    }
    int cnt = 0;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); it++){
        if((*it).f <= (*it).s) cnt += (*it).s - (*it).f;
        else cnt += (*it).s;
    }
    cout << cnt;
}

Measured memory_bytes: 4736
#include <bits/stdc++.h>
using namespace std;
#include "string"
#define int long long
#define pi pair<int,int>
#define ff first
#define ss second
#define boost ios_base::sync_with_stdio(false);cin.tie(nullptr)


int32_t main() { 
    boost;
 	int n;
 	cin>>n;
 	int ans=0;
 	int pw[1000];
 	pw[0]=0;
 	map<int,int>mp;
 	mp[0]=0;
 	
 	for(int i=1;i<1000;i++){
 		pw[i] = pow(i,5);
 		mp[pw[i]]=i;
 	}
 	int f=1;
 	for(int i=0;i<1000 && f;i++){
 		for(int j=0;j<1000 && f;j++){
 			if(pw[i]-pw[j] == n){
 				cout<<i<<" "<<j<<endl;
 				f=0;
 			}
 			else if(pw[j]-pw[i] == n){
 				cout<<j<<" "<<i<<endl;
 				f=0;
 			}
 			else if(pw[i]+pw[j] == n){
 				cout<<i<<" "<<-j<<endl;
 				f=0;
 			}
 		}
 	}   
}

Measured memory_bytes: 4156
/*
边权为 -1, 2 的二叉树转多叉树，使得 $(-1) ^ {c_i} 2 ^ {d_i}$ 中的 $d_i$ 只与深度有关

父亲对自己的正负号贡献和儿子对自己的正负号贡献拆开，分别为“树权”和“点权”

分类讨论并转移，$O(n ^ 5)$，什么鬼差分后优化为 $O(n ^ 4)$

方案不同当且仅当存在点 “终权” = 树权 * 点权 在两种方案中不同，或者 深度相同的点的进制 在两种方案中不同

于是本题统计方案时要特别注意，无论是树权的组合，还是点权的组合，对于方案数都是没有贡献的，
于是，第 i 层的方案分为两部分，“终权”和点数，点数是需要在转移到第 i 层的时候计算好的，
但是有树权为 1 的点数对答案是没有贡献的，只有在转移到 i + 1 层的时候，才能确定第 i 层的“终权”，
这时才能算上“终权”的贡献，最后一层终权 = 树权，特殊统计

(j - k, -1, x, - 1) (k, 1, y, -1)
[x + k - y, 1] [y + j - k - x, -1]

ntk - (ntj - ntk) = y - x   ntj = 2 * ntk - (y - x)
*/
#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
const int N = 55, Mod = 1e9 + 7;

int n, fans, C[N][N], f[N][N][N];

/* f[i][j][k] ：i 个点，最后一层 j 个点，最后一层有 k 个树权为 1 */
inline void Add(int &x, LL y) { x = ((LL)x + y) % Mod; }

int main()
{
	scanf("%d", &n);
	for (int i = 0; i <= n; ++i) {
		C[i][0] = C[i][i] = 1;
		for (int j = 1; j < i; ++j)
			C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]) % Mod;
	}
	//f[1][1][1] = 1;
	f[1][1][1] = C[n][1];
	for (int i = 1; i < n; ++i)
	for (int j = 1; j <= i; ++j)
	for (int k = 0; k <= j; ++k) {
		for (int deta = -(j - k); deta <= k; ++deta)
		for (int ntk = 0; i + ntk <= n; ++ntk) {
			int ntj = 2 * ntk - deta;
			if (ntj < 0) continue;
			if (i + ntj > n) break;
			//Add(f[i + ntj][ntj][ntk], (LL)f[i][j][k] * C[n - i][ntj] % Mod * C[ntj][ntk] % Mod * C[j][k - deta]);
			Add(f[i + ntj][ntj][ntk], (LL)f[i][j][k] * C[n - i][ntj] % Mod * C[j][k - deta]);
		}
	}
	fans = 0;
	for (int i = 1; i <= n; ++i)
		for (int j = /*1*/ 0; j <= n; ++j) {
			//Add(fans, (LL)f[n][i][j]);
			Add(fans, (LL)f[n][i][j] * C[i][j]);
		}
	printf("%d\n", (fans % Mod + Mod) % Mod);

	return 0;
}


Measured memory_bytes: 768
A = int(input())
B = int(input())
C = int(input())
X = int(input())
ans = 0
for i in range(A+1):
    for j in range(B+1):
        for k in range(C+1):
            if i*500 + j*100 + k*50 == X:
                ans += 1
print(ans)

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

int main(){
  int N;
  cin >> N;
  if(N==1){cout << 1 << endl; return 0;}
  vector<int> x(N),y(N),q(N);
  for(int i=0;i<N;i++){cin >> x[i] >> y[i];}
  //ort(q.begin(),q.end());
  int ans=1;
  vector<pair<int,int>> p;
  for(int i=0;i<N;i++){
    for(int j=0;j<N;j++){
      if(i==j)continue;
      p.push_back(make_pair(x[i]-x[j],y[i]-y[j]));
    }
  }
  sort(p.begin(),p.end());
  int cnt=0;
  int P=p.size();
  for(int i=0;i<P;i++){
    int tmp=1;
    while(i+1<P && p[i].first==p[i+1].first && p[i].second==p[i+1].second){
      tmp++; i++;
    }
    cnt=max(cnt,tmp);
  }
  cout << N-cnt << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <cmath>
#include <complex>
#include <string>
#include <sstream>
#include <limits>
#include <algorithm>
#include <functional>

#include <vector>

using namespace std;

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

	int N;
	cin >> N;

	vector<int> button_list(N, 0);

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

	vector<bool> visited(N, false);
	int curr = 0;
	int depth = 0;
	while (visited[curr] == false)
	{
		if (curr == 1)
		{
			visited[curr] = true;
			break;
		}

		visited[curr] = true;
		curr = button_list[curr];
		depth++;
	}

	if (visited[1])
		cout << depth;
	else
		cout << -1;

	return 0;
}

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;
typedef pair<ll,ll> pll;
const ll mod=1e9+7;
//const ll mod=998244353;
const ll inf=5e18;

int main() {
  ll n,m;
  cin >> n >> m;
  vec a(n);
  for(ll i=0;i<n;i++) {
    cin >> a[i];
  }
  a[0]%=m;
  for(ll i=0;i<n-1;i++) {
    (a[i+1]+=a[i])%=m;
  }
  map<ll,ll> count;
  for(ll i=0;i<n;i++) {
    count[a[i]]++;
  }
  ll ans=0;
  for(auto p:count) {
    ans+=p.second*(p.second-1)/2;
    if(p.first==0) {
      ans+=p.second;
    }
  }
  cout << ans << endl;
}

Measured memory_bytes: 4992
f = [False for i in range(100001)]
c = [0 for i in range(100001)]

for i in range(2, 100001):
    if not f[i]:
        for j in range(2*i, 100001, i):
            f[j] = True
for i in range(3, 100001, 2):
    if not f[i] and not f[int((i+1)/2)]:
        c[i] += 1
for i in range(3, 100001):
    c[i] += c[i-1]
    
n = int(input())
while n:
    l, r = list(map(int, input().split()))
    print (c[r]-c[l-1])
    n -= 1


Measured memory_bytes: 7192
from collections import Counter, defaultdict
import sys
sys.setrecursionlimit(10 ** 5 + 10)
# input = sys.stdin.readline
from math import factorial
import heapq, bisect
import math
import itertools
# from copy import deepcopy, copy

import queue
from collections import deque



def main():
    high, width, num = map(int, input().split())
    s_h, s_w = map(int, input().split())
    data1 = list(input())
    data2 = list(input())

    nokori = s_h - 1
    count = 0
    for i in range(num):
        if data1[i] == 'U':
            count += 1
        if count > nokori:
            print('NO')
            sys.exit()
        if data2[i] == 'D' and s_h - count < high:
            count -= 1

    nokori = s_w - 1
    count = 0
    for i in range(num):
        if data1[i] == 'L':
            count += 1
        if count > nokori:
            print('NO')
            sys.exit()
        if data2[i] == 'R' and s_w - count < width:
            count -= 1

    nokori = high - s_h
    count = 0
    for i in range(num):
        if data1[i] == 'D':
            count += 1
        if count > nokori:
            print('NO')
            sys.exit()
        if data2[i] == 'U' and s_h - 1 + count > 0:
            count -= 1

    nokori = width - s_w
    count = 0
    for i in range(num):
        if data1[i] == 'R':
            count += 1
        if count > nokori:
            print('NO')
            sys.exit()
        if data2[i] == 'L' and s_w - 1 + count > 0:
            count -= 1
        # print(count)

    print('YES')



if __name__ == '__main__':
    main()


Measured memory_bytes: 70728
#include <bits/stdc++.h>
#define PI acos(-1)
using namespace std;
int main()
{
    int n,a;
    cin>>n;
    int b[n+10]={0};
    int m=n-1;
    while(m--)
    {
        cin>>a;
        b[a]++;
    }
    for(int i=1; i<=n; i++)
    {
        cout<<b[i]<<"\n";
    }
}


Measured memory_bytes: 4404
# coding: UTF-8
import sys
#sys.setrecursionlimit(n)
import heapq
import re
import bisect
import random
import math
import itertools
from collections import defaultdict, deque
from copy import deepcopy
from decimal import *

n = int(input())
def make_divisors(n):
    divisors = []
    for i in range(1, int(n**0.5)+1):
        if n % i == 0:
            divisors.append(i)
            if i != n // i:
                divisors.append(n//i - 1)
    # divisors.sort()
    return divisors

l = make_divisors(n)
ans = 0
for i in l:
    a = int(n / i)
    q = n % i
    if a == q:
        ans += i
print(ans)

Measured memory_bytes: 6468
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <bitset>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include <iomanip>
#include <cassert>
//#include <utility>
//#include <memory>
//#include <functional>
//#include <deque>
//#include <cctype>
//#include <ctime>
//#include <numeric>
//#include <list>
//#include <iomanip>

//#if __cplusplus >= 201103L
//#include <array>
//#include <tuple>
//#include <initializer_list>
//#include <forward_list>
//
//#define cauto const auto&
//#else

//#endif

using namespace std;


typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;

#define VV(T) vector<vector< T > >

template <class T>
void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()) {
	v.assign(a, vector<T>(b, t));
}

template <class F, class T>
void convert(const F &f, T &t) {
	stringstream ss;
	ss << f;
	ss >> t;
}

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define reep(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) reep((i),0,(n))
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define F first
#define S second
#define mkp make_pair
#define RALL(v) (v).rbegin(),(v).rend()
#define DEBUG
#ifdef DEBUG
#define dump(x)  cout << #x << " = " << (x) << endl;
#define debug(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
#else
#define dump(x)
#define debug(x)
#endif

#define MOD 1000000007LL
#define EPS 1e-8
#define INF 0x3f3f3f3f
#define INFL 0x3f3f3f3f3f3f3f3fLL
#define maxs(x,y) x=max(x,y)
#define mins(x,y) x=min(x,y)

string ans[2] = {"USAGI", "NEKO"};

void mainmain() {
	int n, m;
	int c[2];
	cin >> n >> c[0] >> c[1] >> m;
	map<int, pii> a[2];
	vvint cnt;
	initvv(cnt, 4, n, 0);
	rep(i, n) rep(j, n) {
		int t;
		cin >> t;
		a[0][t] = pii(i, j);
	}
	rep(i, n) rep(j, n) {
		int t;
		cin >> t;
		a[1][t] = pii(i, j);
	}
	vint d(2);
	vint cnt1(4);
	rep(i, m) {
		int t;
		cin >> t;
		if(a[0].count(t)) {
			pii p = a[0][t];
			if(n == ++cnt[2 * 0 + 0][p.F]) d[0]++;
			if(n > 1 && n == ++cnt[2 * 0 + 1][p.S]) d[0]++;
			if(n > 1 && p.F == p.S && n == ++cnt1[0]) d[0]++;
			if(n > 1 && p.F == n - 1 - p.S && n == ++cnt1[1]) d[0]++;
		}
		if(a[1].count(t)) {
			pii p = a[1][t];
			if(n == ++cnt[2 * 1 + 0][p.F]) d[1]++;
			if(n > 1 && n == ++cnt[2 * 1 + 1][p.S]) d[1]++;
			if(n > 1 && p.F == p.S && n == ++cnt1[2]) d[1]++;
			if(n > 1 && p.F == n - 1 - p.S && n == ++cnt1[3]) d[1]++;
		}
		bool f1 = (d[0] >= c[0]);
		bool f2 = (d[1] >= c[1]);
		if(f1 && f2) break;
		if(f1) {
			cout << ans[0] << endl;
			return;
		}
		if(f2) {
			cout << ans[1] << endl;
			return;
		}
	}
	cout << "DRAW" << endl;
}


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

Measured memory_bytes: 21152