akhauriyash/Code-Regression huggingface dataset:
# include "bits/stdc++.h"
using namespace std;
using LL = long long;
using ULL = unsigned long long;
const double PI = acos(-1);
template<class T>constexpr T INF() { return ::std::numeric_limits<T>::max(); }
template<class T>constexpr T HINF() { return INF<T>() / 2; }
template <typename T_char>T_char TL(T_char cX) { return tolower(cX); };
template <typename T_char>T_char TU(T_char cX) { return toupper(cX); };
typedef pair<LL, LL> pii;
const int vy[] = { -1, -1, -1, 0, 1, 1, 1, 0 }, vx[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
const int dx[4] = { 0,1,0,-1 }, dy[4] = { 1,0,-1,0 };
int popcnt(unsigned long long n) { int cnt = 0; for (int i = 0; i < 64; i++)if ((n >> i) & 1)cnt++; return cnt; }
int d_sum(LL n) { int ret = 0; while (n > 0) { ret += n % 10; n /= 10; }return ret; }
int d_cnt(LL n) { int ret = 0; while (n > 0) { ret++; n /= 10; }return ret; }
LL gcd(LL a, LL b) { if (b == 0)return a; return gcd(b, a%b); };
LL lcm(LL a, LL b) { LL g = gcd(a, b); return a / g*b; };
# define ALL(qpqpq)           (qpqpq).begin(),(qpqpq).end()
# define UNIQUE(wpwpw)        sort(ALL((wpwpw)));(wpwpw).erase(unique(ALL((wpwpw))),(wpwpw).end())
# define LOWER(epepe)         transform(ALL((epepe)),(epepe).begin(),TL<char>)
# define UPPER(rprpr)         transform(ALL((rprpr)),(rprpr).begin(),TU<char>)
# define FOR(i,tptpt,ypypy)   for(LL i=(tptpt);i<(ypypy);i++)
# define REP(i,upupu)         FOR(i,0,upupu)
# define INIT                 std::ios::sync_with_stdio(false);std::cin.tie(0)
# pragma warning(disable:4996)

LL n, q;
LL a[101010];

int main() {
	cin >> n >> q;
	REP(i, n)cin >> a[i];
	REP(qqq, q) {
		LL x;
		cin >> x;
		LL sum = 0, ans = 0, k = 0;
		for (int i = 0; i<n; i++) {
			sum += a[i];
			while (sum>x) {
				sum -= a[k];
				k++;
			}
			ans += (i - k + 1);
		}
		cout << ans << endl;
	}
}


Measured memory_bytes: 3868
import java.util.Scanner;

public class Main{
    static boolean ff=false;
    static long maxx(int tot,int ind,int[] c,int ulev[][],int x){
        if(ind>=c.length){
            long[] t=new long[ulev[0].length];
            for(int j=0;j<c.length;j++){
                int i= ((1<<j)&tot);
                if(i!=0){
                    for(int k=0;k<ulev[0].length;k++){
                        t[k]=t[k]+ulev[j][k];
                    }
                }
            }
            long ij=0;
            for(int j=0;j<t.length;j++){
                    if(t[j]>=x){
                        ij++;
                    }
            }
            if(ij==t.length){
                ff=true;
                return 0;
            }else{
                return Integer.MAX_VALUE;
            }

        }
        return Math.min( maxx(tot|(1<<ind),ind+1,c,ulev,x)+c[ind],maxx(tot,ind+1,c,ulev,x) );

    }

    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n= scanner.nextInt();
        int m=scanner.nextInt();
        int x=scanner.nextInt();
        int[] c=new int[n];
        int[][] ul=new int[n][m];
        for(int j=0;j<n;j++){
            c[j]= scanner.nextInt();
            for(int i=0;i<m;i++){
                ul[j][i]=scanner.nextInt();
            }
        }
        ff=false;
        long ans=maxx(0,0,c,ul,x);
        if(!ff){
            System.out.println(-1);
        }else{
        System.out.println(ans);
    }}

}


Measured memory_bytes: 29752
n = int(input())
mod = 10 ** 9 + 7
memo = [{} for _ in range(n+1)]


def AGCin(s):
    for i in range(len(s) - 2):
        if s[i] == 'A' and s[i+1] == 'G' and s[i+2] == 'C':
            return True
    return False


def isok(last4):
    if AGCin(last4):
        return False
    for i in range(3):
        last4_ = [c for c in last4]
        tmp = last4_[i]
        last4_[i] = last4_[i+1]
        last4_[i+1] = tmp
        if AGCin(''.join(last4_)):
            return False
    return True


def dfs(i, last3):
    if i == n:
        return 1
    if last3 in memo[i]:
        return memo[i][last3]
    ret = 0
    for c in 'AGCT':
        last4 = last3 + c
        if isok(last4):
            new_last3 = last4[1:]
            delta = dfs(i+1, new_last3)
            memo[i+1][new_last3] = delta
            ret = (ret + delta) % mod
    return ret


print(dfs(0, 'TTT'))

Measured memory_bytes: 3872
#include <stdio.h>
int main(void){
  int a,b,c,d=0;
  scanf("%d %d",&a,&b);
  d=a+b;
  c=d/2;
  if(d%2==0){
    printf("%d\n",c);
  }else{
  printf("IMPOSSIBLE\n");
}
  return 0;
}


Measured memory_bytes: 128
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = s; i < (int)(n); i++)
#define chmax(a, b) a = max(a, b)
#define chmin(a, b) a = min(a, b)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()

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

//const ll INF = 1e18L + 5;
//const int INF = 1e9 + 5;
//const double pi = 3.14159265358979323846;

void	solve()
{
	int n, m, k;
	cin >> n >> m >> k;
	vector<int> a(n), b(m);
	rep(i, n) cin >> a[i];
	rep(i, m) cin >> b[i];
	ll t = accumulate(all(b), 0L);
	int j = m;
	int ans = 0;
	rep(i, n + 1) {
		while (j > 0 && t > k) {
			j--;
			t -= b[j];
		}
		if (t > k) break;
		ans = max(ans, i + j);
		if (i == n) break;
		t += a[i];
	}
	cout << ans << endl;
}

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

	solve();
}



Measured memory_bytes: 4792
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<set>
#include<queue>
#include<string>
#include<sstream>
#include<iostream>
#include<sstream>
#include<stack>
#include<map>
#include<vector>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;


int main()
{
	long long int n, num=0;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		num += i;
	}
	cout << num;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
 
#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=(int)(a);i<(int)(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)
 
#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=(int)(a)-1;i>=(int)(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)
 
#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define bit(n) (1LL<<(n))
 
// #define DEBUG
 
#ifdef DEBUG
    #define dump(...) fprintf(stderr, __VA_ARGS__)
#else
    #define dump(...)
#endif
 
template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;}
template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;}
 
using namespace std;
using ll=long long;
using vi=vector<int>;
using vll=vector<ll>;
 
const double EPS = 1e-10;
const double PI = acos(-1.0);
const int inf = INT_MAX;
const ll INF = LLONG_MAX;
const ll MOD = 1000000007LL;
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
 
ll extgcd(ll a,ll b,ll& x,ll& y){x=1,y=0;ll g=a;if(b!=0) g=extgcd(b,a%b,y,x),y-=a/b*x;return g;}
ll ADD(const ll &a, const ll &b, const ll mod=MOD) { return (a+b)%mod;}
ll SUB(const ll &a, const ll &b, const ll mod=MOD) { return (a-b+mod)%mod;}
ll MUL(const ll &a, const ll &b, const ll mod=MOD) { return (1LL*a*b)%mod;}
ll DIV(const ll &a, const ll &b, const ll mod=MOD) {ll x,y; extgcd(b,mod,x,y);return MUL(a,(x+mod)%mod,mod);}
 
int main(void){
    cin.tie(0);
    ios::sync_with_stdio(false);

    string in; cin >> in;
    int res = 700;
    for(auto& e : in){
        res += (e == 'o' ? 100:0);
    }

    cout << res << endl;

    return 0;
}


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

void ch(int H, int W){
  for (int i = 0; i < H; ++i) {
    for(int j = 0; j < W; ++j) {
     if((i + j) % 2 == 0){
       printf("#");
     }else{
       printf(".");
     }
    } 
    printf("\n");     
  }
}

int main(){
  int H,W;

  while(1){
    scanf("%d%d", &H,&W); 
    if(H == 0 && W == 0) return 0;
    
    ch(H, W);
    printf("\n");
  }
}

Measured memory_bytes: 1000
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e18,MOD = 1e9 + 7;
const int INT_INF = 1e9,INT_MOD=1e9+7;
#define rep(i, N) for(int i = 0; i < N; i++)
typedef pair<int, int> Pi;
typedef pair<double, double> P;
signed main(){
    string s,t;cin>>s>>t;

    int a,b;cin>>a>>b;
    string u;cin>>u;
    if(s==u)cout<<a-1<<" "<<b<<endl;
    else cout<<a<<" "<<b-1<<endl;

    return 0;
}

Measured memory_bytes: 256
import Control.Applicative
import Control.Monad
import Data.List

main :: IO ()
main = do
    n <- readLn :: IO Int
    ss <- getLine
    ts <- getLine
    let as = do
            (i, bs) <- zip [0..] (tails ss)
            let cs = take (length bs) ts
            guard $ bs == cs
            return i
    print $ head as + length ts

Measured memory_bytes: 508
package main

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

type stringSorter []byte

func (ss stringSorter) Len() int {
	return len(ss)
}

func (ss stringSorter) Less(i, j int) bool {
	return ss[i] < ss[j]
}

func (ss stringSorter) Swap(i, j int) {
	ss[i], ss[j] = ss[j], ss[i]
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Scan()
	n, _ := strconv.Atoi(sc.Text())

	mp := make(map[string]int)

	for i := 0; i < n; i++ {
		sc.Scan()
		sort.Sort(stringSorter(sc.Bytes()))

		mp[sc.Text()]++
	}

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


Measured memory_bytes: 9728
import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class Main {
	int N, K;
	String S;
	boolean[] origin;
	List<Range> ranges;
	int result = 0;

	static class Range {
		int from, to;

		Range(int from, int to) {
			this.from = from;
			this.to = to;
		}
	}

	Main() throws IOException {
		InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
		BufferedReader in = new BufferedReader(reader);
		String[] tokens = in.readLine().split(" ");
		N = Integer.parseInt(tokens[0]);
		K = Integer.parseInt(tokens[1]);
		S = in.readLine();
		in.close();
		this.origin = new boolean[N];
		for (int i = 0; i < S.length(); ++i) {
			if (S.charAt(i) == '0') {
				origin[i] = false;
			} else {
				origin[i] = true;
			}
		}
		Deque<Range> queue = new ArrayDeque<>();
		for (int i = 0; i < this.origin.length; ++i) {
			if (!this.origin[i]) {
				if (queue.isEmpty()) {
					queue.addLast(new Range(i, i + 1));
				} else {
					Range last = queue.getLast();
					if (last.to == i) {
						last.to = i + 1;
					} else {
						queue.addLast(new Range(i, i + 1));
					}
				}
			}
		}
		this.ranges = new ArrayList<>(queue.size());
		this.ranges.addAll(queue);

		calc();
	}

	void calc() {
		if (this.ranges.size() <= K) {
			// 全体にできる
			this.result = N;
		} else {
			for (int i = 0; i + K - 1 < this.ranges.size(); ++i) {
				this.result = Math.max(this.result, sub(i));
			}
		}
	}

	int sub(int rangeStart) {
		int from = this.ranges.get(rangeStart).from;
		int to = this.ranges.get(Math.min(rangeStart + K - 1, this.ranges.size() - 1)).to;

		int result = to - from;
		for (int i = from - 1; i >= 0; --i) {
			if (!this.origin[i]) {
				break;
			}
			++result;
		}
		for (int i = to; i < this.origin.length; ++i) {
			if (!this.origin[i]) {
				break;
			}
			++result;
		}
		// System.out.println(from + ", " + to + ", " + result);
		return result;
	}

	public static void main(String[] args) throws IOException {
		Main ins = new Main();
		System.out.println(ins.result);
	}

}

Measured memory_bytes: 27092
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
 
#define rep(i,j) REP((i), 0, (j))
#define REP(i,j,k) for(int i=(j);(i)<(k);++i)
#define between(a,x,b) ((a)<=(x)&&(x)<=(b))
#define INF 1 << 28
 
using namespace std;
 
int n, m;
int cost[400][400];
 
int main(){
  scanf("%d%d", &n, &m);
  rep(i, n) rep(j, n) cost[i][j] = 0;
  int a, b, c;
  rep(i, m){
    scanf("%d%d%d", &a, &b, &c);
    cost[a][b]  = c;
  }
 
  rep(k, n) rep(i, n) rep(j, n)  if(cost[i][k] && cost[k][j]) // if(i != j && k != i && k != j)
    cost[i][j] = max(cost[i][j], cost[i][k] + cost[k][j]);
 
  /*  rep(i, n){
    rep(j, n) printf("%d ", cost[i][j]);
    puts("");
    }*/
 
  printf("%d\n", cost[0][n-1]);
  return 0;
}

Measured memory_bytes: 1652
main = do
  s <- getContents
  let v = map (map read . words) . lines $ s
  let w = map solve v
  let x = map (\x-> if x then "YES" else "NO") $ w
  mapM_ putStrLn x

solve::[Double] -> Bool
solve [xa,ya,xb,yb,xc,yc,xd,yd] =
  abs(dot u v)/len(u)/len(v) < eps
  where u = (xb-xa, yb-ya)
        v = (xd-xc, yd-yc)
        dot (a,b) (c,d) = a*c + b*d
        len (a,b) = sqrt(a^2+b^2)
        eps=1e-6

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

int main() {
	int num, n;
	while (cin >> num) {
		int sum = 0;
		if (num == 0) break;
		for (int i = 0; i < 9; i++) {
			cin >> n;
			sum += n;
		}
		cout << num - sum << endl;
	}
	return 0;
}

Measured memory_bytes: 2996
pub fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

pub fn read_col<T: std::str::FromStr>(n: u32) -> Vec<T> {
    (0..n).map(|_| read()).collect()
}

use std::collections::VecDeque;
use std::fmt::Display;

fn delete(vd: &mut VecDeque<String>, key: &String) {
    let l = vd.len();
    let mut i = 0;
    while i < l {
        if *key == vd[i] {
            break;
        }
        i += 1;
    }
    if i < l {
        vd.remove(i as usize);
    }
}

fn print_vec_deque<T: Display>(a: &VecDeque<T>, n: usize) {
    for i in 0..n {
        print!("{}", a[i]);
        if i == n - 1 {
            println!("");
        } else {
            print!(" ");
        }
    }
}

fn main() {
    let n: u32 = read();
    let commands: Vec<String> = read_col(n);

    let mut vd: VecDeque<String> = VecDeque::new();

    for c in commands {
        if c == "deleteFirst" {
            vd.pop_front();
        } else if c == "deleteLast" {
            vd.pop_back();
        } else {
            let tmp: Vec<String> = c
                .trim()
                .split_whitespace()
                .map(|e| e.parse().ok().unwrap())
                .collect();
            let cmd = &tmp[0];
            let key = &tmp[1];

            if cmd == "insert" {
                vd.push_front(key.clone());
            } else {
                delete(&mut vd, key);
            }
        }
    }

    print_vec_deque(&vd, vd.len() as usize);
}



Measured memory_bytes: 107768
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner in = new java.util.Scanner(System.in);
	
		int max = 0;
		int sum = 0;
		for(int i=0; i<3; i++){
			int d = in.nextInt();
			if(max < d){
				max = d;
			}
			sum += d;
		}
		sum -= max;
		
	
		System.out.println(sum);
	
		
	}
}


Measured memory_bytes: 23764
#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
using ll = long long;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define REP(i, n) for(int i = 0; i < n; i++)

struct Edge{
    int from;
    int to;
    int d;
};

using Graph = vector<vector<Edge>>;

int main(){
    int n;
    cin>>n;
    Graph G(n);
    int u,v,w;
    for(int i=0;i<n-1;i++){
        cin>>u>>v>>w;
        Edge tmp;
        tmp.to = v-1;
        tmp.d = w;
        G[u-1].push_back(tmp);
        tmp.to = u-1;
        G[v-1].push_back(tmp);
    }

    vector<int> dist(n,-1);
    queue<int> que;

    dist[0] = 0;
    que.push(0);

    vector<int> ans(n,0);

    while(!que.empty()){
        int pv = que.front();
        que.pop();

        for(auto nv : G[pv]){
            if(dist[nv.to] != -1) continue;

            dist[nv.to] = dist[pv] + nv.d;
            if(dist[nv.to] % 2 == 0) ans[nv.to] = 0;
            else ans[nv.to] = 1;
            que.push(nv.to);
        }
    }
    for(int i=0;i<n;i++) cout<<ans[i]<<endl;
}

Measured memory_bytes: 7680
import sys

def prepare(X):
    N = 101
    List = [X] * N
    for i in range(0, 50):
        List[2*i+1] = X-i-1
        List[2*i+2] = X+i+1
    return List

def remove(List, N, PList):
    for Num in range(N):
        if(PList[Num] in List):
            List.pop( List.index(PList[Num]) )
    print(List[0])
if(__name__ == "__main__"):

    XY = input().strip().split()
    X = int(XY[0])
    N = int(XY[1])

    PList = [0] * N
    if(N > 0):
        P_str = input().strip().split()

        for i in range(N):
            PList[i] = int( P_str[i] )

        List = prepare(X)
        remove(List, N, PList)
    else:
        print(X)


Measured memory_bytes: 9236
import copy
N = int(input())
S = input()
SS = list(copy.deepcopy(S))
cnt = 0
for i in range(N):
  if S[i] == "(":
    cnt += 1
  else:
    cnt -= 1
  if cnt < 0:
    SS.insert(0,"(")
    cnt = 0
if cnt > 0:
  for j in range(cnt):
    SS.append(")")
print(*SS,sep="")

Measured memory_bytes: 3572
n = int(input())
monsters = list(map(int, input().split()))
braves = list(map(int, input().split()))
destroys = 0
for i in range(n):
    if braves[i] > monsters[i]:
        destroys += monsters[i]
        braves[i] -= monsters[i]

        if braves[i] > monsters[i + 1]:
            destroys += monsters[i + 1]
            monsters[i + 1] = 0
        
        else:
            destroys += braves[i]
            monsters[i + 1] -= braves[i]
    else:
        destroys += braves[i]
print(destroys)


Measured memory_bytes: 24168
#include <iostream>
#include <iomanip>
#include <vector>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <queue>
#include <deque>
#include <stack>
#include <algorithm>
#include <numeric>
#include <string>
#include <sstream>
#include <cmath>
#include <cstring>
#include <assert.h>
#include <utility>
#include <tuple>
#include <array>
#include <cstdlib>

using int64 = long long;

static int query_count = 0;

std::string query(int i) {
    query_count++;

    assert(query_count <= 20);

    std::cout << i << std::endl;
    std::string response;
    std::cin >> response;

    if (response == "Vacant") exit(0);
    return response;
}

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

    int N;
    std::cin >> N;

    std::vector<int> evens;
    for (int i = 0; i < N; i += 2) {
        evens.push_back(i);
    }

    int lb = 0, ub = evens.size();

    std::string state = query(evens[0]);

    while (ub - lb > 1) {
        int mid = (ub + lb) / 2;

        std::string response = query(evens[mid]);

        if (response == state) {
            lb = mid;
        } else {
            ub = mid;
        }
    }

    query(evens[lb] + 1);

    return 0;
}


Measured memory_bytes: 1236
n = int(input())
L = []
for i in range(n):
    b,f,r,v = map(int, input().split())
    L.append([b,f,r,v])

A = [ [ [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0] ],

      [ [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0] ],

      [ [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0] ],

      [ [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0] ] ]

for j in range(len(L)):
    A[L[j][0]-1][L[j][1]-1][L[j][2]-1] += L[j][3]
for a in range(3):
    for b in range(3):
        print('',*A[a][b])
    print('#'*20)
for b in range(3):
    print('',*A[3][b])


Measured memory_bytes: 5636
N,M=gets.chomp.split.map(&:to_i)
A=gets.chomp.split.map(&:to_i).sort.reverse
B=gets.chomp.split.map(&:to_i).sort.reverse
MOD = 1000000007

if A.size != A.uniq.size || B.size != B.uniq.size
  puts 0
  exit
end

i=0
j=0
ans = 1
(N*M).downto(1) do |k|
  if A[i] == k && B[j] == k
    i += 1
    j += 1
    next
  end
  
  if A[i] == k
    ans = ans * j % MOD
    i += 1
  elsif B[j] == k
    ans = ans * i % MOD
    j += 1
  else
    ans = ans * (i * j - N*M + k) % MOD
  end
end

puts ans



Measured memory_bytes: 3960
import bisect
import sys

input = sys.stdin.readline

# 素因数分解
def prime_factorize(n):
    a = []
    while n % 2 == 0:
        a.append(2)
        n //= 2
    f = 3
    while f * f <= n:
        if n % f == 0:
            a.append(f)
            n //= f
        else:
            f += 2
    if n != 1:
        a.append(n)
    return a

def main():
    N = 100001
    prime = []
    for i in range(3, N):
        tmp = prime_factorize(i)
        if len(tmp) == 1:
            prime.append(i)
    
    primes = []
    for p in prime:
        k = (p+1)//2
        tmp = prime_factorize(k)
        if len(tmp) == 1:
            primes.append(p)

    Q = int(input())
    for _ in range(Q):
        l, r = map(int, input().split())
        ans = bisect.bisect_right(primes, r) - bisect.bisect_left(primes, l)
        print(ans)

if __name__ == "__main__":
    main()


Measured memory_bytes: 4288
import java.util.*;

public class Main {
    void run() {
        Scanner sc = new Scanner(System.in);
        int k = sc.nextInt();
        int a = sc.nextInt();
        int b = sc.nextInt();
        boolean ans = false;
        for (int i = a; i<= b; i++) {
            if (i % k == 0) {
                ans = true;
                break;
            }
        }
        System.out.println(ans? "OK": "NG");
    }

    void debug(Object... os) {
        System.err.println(Arrays.deepToString(os));
    }

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


Measured memory_bytes: 35800
#include <bits/stdc++.h>
using namespace std;
#define rep(i, N) for (long long i = 0; i < N; i++)
using ll = long long;
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;
}
const long long INF = 1LL << 60;

int main() {
    ll N, W;
    cin >> N >> W;
    vector<pair<ll, ll>> wv(N + 1);
    for (ll i = 1; i <= N; i++) {
        cin >> wv[i].first >> wv[i].second;
    }

    vector<vector<ll>> dp(N + 1, vector<ll>(100100));
    rep(i, N + 1) {
        rep(j, 100100) { dp[i][j] = INF; }
    }
    dp[0][0] = 0;
    for (ll i = 1; i <= N; i++) {
        for (ll j = 0; j < 100100; j++) {
            if (j - wv[i].second >= 0) {
                chmin(dp[i][j], dp[i - 1][j - wv[i].second] + wv[i].first);
            }
            chmin(dp[i][j], dp[i - 1][j]);
        }
    }
    ll ans = 0;
    rep(j, 100100) {
        if (dp[N][j] <= W) {
            ans = max(ans, j);
        }
    }
    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 80256
#include <stdio.h>
int main(void)
{
    int n,ans=0;
    scanf("%d", &n);
    int v[n], c[n];
    for(int i=0; i<n; i++) scanf("%d", &v[i]);
    for(int i=0; i<n; i++) scanf("%d", &c[i]);
    for(int i=0; i<n; i++)
    {
        if(v[i]>c[i]) ans+=v[i]-c[i];
    }
    printf("%d", ans);
    return 0;
}

Measured memory_bytes: 128
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <math.h>
#include <numeric>
#include <complex>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <unordered_map>
#include <set>
#include <bitset>
#include <functional>
#include <assert.h>
using ll=long long;
#define int ll
#define rng(i,a,b) for(int i=int(a);i<int(b);i++)
#define rep(i,b) rng(i,0,b)
#define gnr(i,a,b) for(int i=int(b)-1;i>=int(a);i--)
#define per(i,b) gnr(i,0,b)
#define eb emplace_back
#define all(x) x.begin(),x.end()
#define SZ(x) ((int)x.size())
#define fi first
#define se second
const int INF = 1e15;
using namespace std;

template<class T> using vc=vector<T>;
template<class T> using vvc=vc<vc<T>>;

using pi=pair<int,int>;
using vi=vc<int>;

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

signed main() {
    cin.tie(0);
    ios::sync_with_stdio(0);
    cout<<fixed<<setprecision(20);

    string S,T; cin >> S >> T;
    int ans=0;
    rep(i,SZ(S)-SZ(T)+1) {
        int cnt=0;
        rep(j,SZ(T)) {
            if(S[i+j]==T[j]) cnt++;
        }
        chmax(ans,cnt);
    }
    cout << SZ(T)-ans << endl;
}

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

int f(long long a, long long b) {
	int digit=0;
	a = max(a, b);
	while (a > 0) {
		a /= 10;
		digit += 1;
	}
	return digit;
}

int main() {
	int ans;
	long long n,a,b;
	cin >> n;
	rep(i, 1, sqrt(n)) {
		if (n%i == 0) {
			a = i;
			b = n / i;
		}
	}
	ans = f(a, b);
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 384
N = int(input())
TA = [list(map(int,input().split())) for _ in range(N)]

lcms = TA[0]

for t,a in TA[1:]:
    tmp = [t,a]

    
    m1 = (lcms[0]+tmp[0]-1)//tmp[0]
    m2 = (lcms[1]+tmp[1]-1)//tmp[1]
    
    m = max(m1,m2)
    if m != 0:
        tmp[0] *= m
        tmp[1] *= m
    lcms = tmp

print(sum(lcms))


Measured memory_bytes: 3188
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Node{

  int key;
  struct Node *left;
  struct Node *right;
  struct Node *parent;

};
struct Node *root,*NIL;

void insert(int );
void inorder(struct Node *);
void preorder(struct Node *);

int main(){

  int i,sumnode,inputdata;
  char cinsert[100];  

  scanf("%d",&sumnode);

  for(i = 0; i < sumnode; i++){

  scanf("%s",&cinsert);

  if((strcmp(cinsert,"insert")) == 0){

    
    scanf("%d",&inputdata);

      insert(inputdata);

  }

  else if((strcmp(cinsert,"print")== 0 )){

	inorder(root);
	printf("\n");
	preorder(root);
	printf("\n");

      }


  }

  return 0;
}

void insert(int k){

  struct Node *x = root,*y = NIL, *z;

  

  z = (struct Node *)malloc(sizeof(struct Node));

  z->key = k;
  z->right = NIL;
  z->right = NIL;


  while(x != NIL){

    y = x;

    if(z->key < x->key){

      x = x->left;

    }

    else{

      x = x->right;

    }

  }

  z->parent = y;


  if(y == NIL){

    root = z;
  }

  else{

    if(z->key < y->key){

      y->left = z;

    }

    else{

      y->right = z;

    }

  }

}


void inorder(struct Node *u){

  if(u == NIL){

    return ;

  }

  inorder(u->left);

  printf(" %d",u->key);

  inorder(u->right);

}


void preorder(struct Node *u){

  if(u == NIL){

    return;

  }

  printf(" %d",u->key);

  preorder(u->left);
  preorder(u->right);

}

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

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
#ifdef __DEBUG

/**
 * For DEBUG
 * https://github.com/ta7uw/cpp-pyprint
 */
#include "cpp-pyprint/pyprint.h"

#endif

void solve() {
    ll K, A, B;
    cin >> K >> A >> B;
    rep2(i, A, B + 1) {
        if (i % K == 0) {
            cout << "OK" << '\n';
            return;
        }
    }
    cout << "NG" << '\n';
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(15);
    solve();
    return 0;
}


Measured memory_bytes: 3640
#include <bits/stdc++.h>
#define f first
#define s second
#define MOD 1000000007
#define PMOD 998244353
#define pb(x) push_back(x)
using namespace std;

typedef long long int ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> plii;
typedef pair<int, pii> piii;
const int INF = 1e9+10;
const ll LINF = 1LL*INF*INF;
const int MAXN = 2e5+10;
const int MAXM = 5e3+10;

priority_queue<int> pq;
vector<vector<int> > graph;
queue<int> que;

int A[MAXN];
char S[MAXN];

int main()
{
    int n,m,k,a,b,x,y;
    int sum = 0;
    int cnt = 0;
    int mx = 0;
    int mn = INF;
    int cur = 0, idx = -1;

    cin>>a>>b;

    int res = max(a+b,max(a-b,a*b));

    cout<<res<<"\n";


    return 0;
}


Measured memory_bytes: 764
#include<bits/stdc++.h>
#define EPS (1e-10)
#define equals(a,b)(fabs((a)-(b))<EPS)
#define rep(i,n)for(int i=0;i<n;i++)
using namespace std;

struct Point {
	double x, y;
	Point(double x = 0, double y = 0) :x(x), y(y) {}
	Point operator*(double a) { return Point(a*x, a*y); }
	Point operator-(Point p) { return Point(x - p.x, y - p.y); }
};
struct Segment {
	Point p1, p2;
};
double cross(Point a, Point b) {
	return a.x*b.y - a.y*b.x;
}
double dot(Point a, Point b) {
	return a.x*b.x + a.y*b.y;
}
bool isPrallel(Segment s1, Segment s2) {
	return equals(cross(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
bool isOrthogonal(Segment s1, Segment s2) {
	return equals(dot(s1.p2 - s1.p1, s2.p2 - s2.p1), 0.0);
}
int main() {
	double x1, y1, x2, y2, x3, y3, x4, y4;
	while (cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4) {
		Segment s1{ {x1,y1},{x2,y2} };
		Segment s2{ {x3,y3},{x4,y4} };
		puts(isOrthogonal(s1, s2) ? "YES" : "NO");
	}
}

Measured memory_bytes: 3060
#include <algorithm>
#include <bitset>
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// clang-format off
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 * b / gcd(a, b); }
template <typename T> T clamp(T val, T min, T max) { return val < min ? min : (max < val ? max : val); }
template <typename T> size_t max_index(T begin, T end) { return distance(begin, max_element(begin, end)); }
template <typename T> size_t min_index(T begin, T end) { return distance(begin, min_element(begin, end)); }
// clang-format on

#define int long long
#define YES "Yes"
#define NO  "No"

using namespace std;

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

  int n; cin >> n;
  string s; cin >> s;
  int k; cin >> k;

  for (int i = 0; i < n; ++i) {
    if (s[i] != s[k - 1]) s[i] = '*';
    // if (s[i] - s[k] != 0) s[i] = '*';
  }
  cout << s << endl;
  
  // cout << num << endl;
  
  return 0;
}


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

typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define all(x) (x).begin(),(x).end()
#define sz(x) ((int)(x).size())

template<typename T>
T mod(T a, T b){
    return (a + b) % b;
}

template<typename T>
T gcd(T a, T b){
    if (b == 0) return a;
    return gcd(b, a % b);
}

ll lcm(ll a, ll b){
    return a * b / gcd(a,b);
}

// n を素因数分解
map<ll, ll> factor(ll n){
    map<ll, ll> mp;
    for (ll i = 2; i*i <= n; i++) {
        while (n % i == 0) {
            mp[i]++;
            n /= i;
        }
    }

    if (n > 1) {
        mp[n]++;
    }

    return mp;
}

// 文字列に "hoge" が含まれているか
// string str = "hogepiyo";
// if (str.find("hoge") != string::npos) {
//     cout << "文字列が含まれています" << endl;
// }

// char to string
// char c = 'a';
// string str = {c};

void solve(){
    int N;
    cin >> N;

    vi h(N);
    int hmax = 0;
    for (int i = 0; i < N; i++) {
        cin >> h[i];
        hmax = max(hmax, h[i]);
    }

    vvi kadan(hmax, vi(N, 0));
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < h[i]; j++) {
            kadan[j][i] = 1;
        }
    }

    int ans = 0;
    bool maki = false;
    for (int row = 0; row < hmax; row++) {
        for (int col = 0; col < N; col++) {
            if (kadan[row][col] != 0) {
                if (maki == false) {
                    ans++;
                }
                maki = true;
            } else {
                maki = false;
            }
        }
        maki = false;
    }

    cout << ans << endl;

    return;
}

int main(int argc, char const* argv[])
{
    solve();
    return 0;
}


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

const double EPS = 1e-10;
const ll INF = 100000000;
const ll MOD = 1000000007;

int n;
ll l;
string str[100000];
ll grundy = 0;

ll g(ll dep) {
    dep = l-dep+1;
    ll x = 1;
    while (dep%2 == 0) {
        x *= 2;
        dep /= 2;
    }
    return x;
}

void dfs(string& now, ll dep, int& ind) {
    if (ind == n) {
        grundy ^= g(dep);
        return;
    }
    if (now == str[ind]) {
        ind++;
        return;
    }
    if (str[ind].size() < now.size() || now != str[ind].substr(0, now.size())) {
        grundy ^= g(dep);
        return;
    }
    now.push_back('0');
    dfs(now, dep+1, ind);
    now.pop_back();
    now.push_back('1');
    dfs(now, dep+1, ind);
    now.pop_back();
}

int main(){
    cin >> n >> l;
    rep(i,n) {
        cin >> str[i];
    }
    sort(str, str+n);
    int ind = 0;
    string now = "";
    dfs(now, 0, ind);
    if (grundy) {
        cout << "Alice" << endl;
    } else {
        cout << "Bob" << endl;
    }
}
































Measured memory_bytes: 10752
import math
import fractions
import collections
import itertools
def ggcd(a,b):
    if(b==0):
        return a
    return ggcd(b,a%b)
K=int(input())
num=0
a=0
for i in range(1,K+1,1):
    for j in range(1,K+1,1):
        for k in range(1,K+1,1):
            a=ggcd(i,j)
            num=num+ggcd(a,k)

print(num)

Measured memory_bytes: 82356
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>

#include <algorithm>
#include <numeric>
#include <cmath>

using namespace std;
typedef long long ll;
const long double PI = (acos(-1));
const long long MOD = 1000000007;
#define rep(i,n) REP(i,0,n)
#define REP(i,x,n) for(int i=x;i<n;++i)

///////////////////////////////////////////////////
// -------------------- I/O -------------------- //
///////////////////////////////////////////////////
// https://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords
template<typename T> void outputVec(const std::vector<T>& vec, const int precision = 0) {
	if (precision > 0) std::cout << std::fixed << std::setprecision(precision);
	for (auto it = vec.begin(); it != vec.end() - 1; ++it) { std::cout << *it << " "; }
	std::cout << *(vec.end() - 1) << "\n";
}
template<typename T> void outputVal(const T& res, const int precision = 0) {
	if (precision > 0) std::cout << std::fixed << std::setprecision(precision);
	std::cout << res << "\n";
}
template<typename T> T inputVal() { T a; std::cin >> a; return a; }
template<typename T> std::vector<T> inputVec(int N) {
	std::vector<T> vec(N);
	for (auto it = vec.begin(); it != vec.end(); ++it) { std::cin >> *it; }
	return vec;
}
template<typename T> void inputVec(std::vector<T>& vec) {
	for (auto it = vec.begin(); it != vec.end(); ++it) { std::cin >> *it; }
}

///////////////////////////////////////////////////
// ------------------- utils ------------------- //
///////////////////////////////////////////////////
// change min/max
template<class T> inline bool chMin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chMax(T& a, T b) { if (a < b) { a = b; return true; } return false; }

///////////////////////////////////////////////////
// ------------------- main -------------------- //
///////////////////////////////////////////////////
void Main() {
	const int N = inputVal<int>();
	const vector<int> A = inputVec<int>(N);
	vector<int> sa = A;
	sort(sa.begin(), sa.end());

	rep(i, N) {
		if (A[i] == sa[N - 1]) {
			cout << sa[N - 2] << endl;
		}
		else {
			cout << sa[N - 1] << endl;
		}
	}

}

int main() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout << std::fixed << std::setprecision(15);
	Main();

	double tmp;
	cin >> tmp;

	return 0;
}


Measured memory_bytes: 3200
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce


INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007


h, w, a, b = LI()
L1 = [0] * (h + 1)
for i in range(h + 1):
    L1[i] = a * i + (w - a) * (h - i)


L2 = [0] * (w + 1)
for j in range(w + 1):
    L2[j] = b * j + (h - b) * (w - j)


flag = 0
for k in range(h + 1):
    for l in range(w + 1):
        if L1[k] == L2[l]:
            flag = 1
            break
    if flag:
        break


if flag:
    tate = [a] * k + [w - a] * (h - k)
    yoko = [b] * l + [h - b] * (w - l)
    ans = [[0] * w for _ in range(h)]
    for y in range(h):
        for x in range(w):
            if tate[y] and yoko[x]:
                ans[y][x] = 1
                tate[y] -= 1
                yoko[x] -= 1
    for i in range(h):
        print(*ans[i], sep='')
else:
    print('No')

Measured memory_bytes: 78556
import numpy as np
import scipy.sparse as sps
import scipy.misc as spm
import collections as col
import functools as func
import itertools as ite
import fractions as frac
import math as ma
from math import cos,sin,tan,sqrt
import cmath as cma
import copy as cp
import sys
import re
import bisect as bs
sys.setrecursionlimit(10**7)
EPS = sys.float_info.epsilon
PI = np.pi; EXP = np.e; INF = np.inf
MOD = 10**9 + 7

def sinput(): return sys.stdin.readline().strip()
def iinput(): return int(sinput())
def imap(): return map(int, sinput().split())
def fmap(): return map(float, sinput().split())
def iarr(n=0):
    if n: return [0 for _ in range(n)]
    else: return list(imap())
def farr(): return list(fmap())
def sarr(n=0):
    if n: return ["" for _ in range(n)]
    else: return sinput().split()
def adj(n): return [[] for _ in range(n)]

#整数問題セット
def gcd(numbers): return func.reduce(frac.gcd, numbers)
def lcm(numbers): return func.reduce(LCM, numbers)
def inv(a): return pow(a, MOD-2, MOD) #逆元
def comb(n,r):
    ans = 1
    for i in range(r): ans *= n-i; ans *= inv(r-i); ans %= MOD
    return ans

n,a,b = imap()
ans = pow(2,n,MOD) - comb(n,a) - comb(n,b) - 1
print(ans%MOD)


Measured memory_bytes: 37660
#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;

//// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt"


int main() {
	while (1) {
		int N; cin >> N;
		if (!N)break;
		vector<int>v;
		for (int i = 0; i < N; ++i) {
			int sum = 0;
			for (int j = 0; j < 5; ++j) {
				int a; cin >> a; sum += a;
			}
			v.push_back(sum);
		}
		sort(v.begin(), v.end());
		cout << v.back() << " " << v[0] << endl;
	}
	
	return 0;
}

Measured memory_bytes: 3064
# import bisect
# from collections import Counter, defaultdict, deque
# import copy
# from heapq import heappush, heappop, heapify
# from fractions import gcd
# import itertools
# from operator import attrgetter, itemgetter
# import math

import sys

# import numpy as np

ipti = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)

def main():
    n = int(input())
    
    if n % 2 == 0:
        print(n)
    else:
        print(n*2)

if __name__ == '__main__':
    main()

Measured memory_bytes: 38256
#include <iostream>
#include <algorithm>
using namespace std;
int w,h;
int G[100][100];
int sx,sy;
int dx[] = {1,-1,0,0},dy[] = {0,0,-1,1};
int ans; 

void dfs(int px,int py,int cnt){
  if(cnt > 10)return;
  for(int i = 0 ; i < 4 ; i++){

    int nx = px + dx[i],ny = py + dy[i];

    if(!(0 <= nx && nx < w && 0 <= ny && ny < h && G[ny][nx] != 1))continue;
    while(1){
      if(G[ny][nx] == 3){
	ans = min(cnt,ans);
      }
      nx+=dx[i],ny+=dy[i];
      if(!(0 <= nx && nx < w && 0 <= ny && ny < h ))break;
      if(G[ny][nx] == 1){
	G[ny][nx] = 0;
	dfs(nx - dx[i],ny - dy[i],cnt + 1);
	G[ny][nx] = 1;
	break;
      }
    }
  }
}

int main(){
  while( cin >> w >> h,w + h){

    for(int i = 0 ; i < h ; i++){
      for(int j = 0 ; j < w ; j++){
	cin >> G[i][j];
	if(G[i][j] == 2){
	  sx = j;
	  sy = i;
	}
      }
    }

    ans = 11;
    dfs(sx,sy,1);
    cout << (ans > 10?-1:ans) << endl;
  }
}

Measured memory_bytes: 1180
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> lpair;
const ll MOD = 1e9 + 7;
const ll INF = 1e18;
#define REP(i,m,n) for(int i=(int)(m) ; i < (int) (n) ; ++i )
#define rep(i,n) REP(i,0,n)
#define rREP(i,m,n) for(ll i = (m); i >= (n); i--)
#define print(x) cout << (x) << endl;
#define printa(x,n) for(ll i = 0; i < n; i++){ cout << (x[i]) << " ";} cout<<endl;
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;

    int ary[n];

    rep(i,n) cin >> ary[i];

    int cnt = 0;
    rep(i,n) if (ary[ary[i]-1]==i+1) cnt++;
    cout << cnt /2 << endl;
}


Measured memory_bytes: 640
#include<bits/stdc++.h>
#define ll long long
#define pp pair<int,int>
#define ss second
#define ff first
using namespace std;

int main()
{
     int n,c=0;
     cin>>n;
     int a[n];
     for(int i=1;i<=n;i++)
     cin>>a[i];
     for(int i=1;i<=n;i++)
     {
          if(i%2!=0 && a[i]%2!=0)
          c++;
     }
     cout<<c;
}

Measured memory_bytes: 3636
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<tuple>
#define int long long
using namespace std;

signed main() {
 	int N;
 	cin >> N;
 	int answer = 100;
 	for(int i = 1;i * i <= N;i++) {
 		if(N % i == 0) {
 			int A = N / i;
 			int count = 0;
 			while(A != 0) {
 				count++;
 				A = A / 10;
 			}
 			answer = min(answer,count);
 		}
 	}
 	cout << answer << endl;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp>
#define ll long long int
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(),x.end()
#define mem(x,y) memset(x,y,sizeof(x))//memset only use to initialize 0 or -1 no other number.
#define pii pair<int,int>
#define pll pair<ll,ll>
#define INF 1e9
#define INFL 1e18
#define mod 1000000007
//#define mod 998244353
#define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
using namespace std;
using namespace __gnu_pbds; 
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> os;
typedef tree<pii,null_type,less<pii>,rb_tree_tag,tree_order_statistics_node_update> os_pair;

ll power(ll x,ll n){ll res =1;while(n>0){if(n%2==1){res=res*x;}x=x*x;n=n/2;}return res;}
ll powm(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}

//cout<< fixed << setprecision(10)

int main(){

    fast;
    int T;
    T=1;
    //cin>>T;
    while(T--){
    	int n,i,j,k;
    	cin>>n>>k;
    	int a[n];
    	for(i=0;i<n;i++)
    	{
    		cin>>a[i];
		}
		sort(a,a+n);
		int sum=0;
		for(i=0;i<k;i++)
		{
			sum+=a[i];
		}
		cout<<sum;

    }

}

Measured memory_bytes: 3632
#include<stdio.h>
int main()
{
    char a[4];
    int n=0,i;
    scanf("%s",&a);
    for(i=0;i<4;i++)
    {
          if(a[i]=='+')
          {
              n++;
          }
          else
          {
              n--;    
          }
    }
    printf("%d",n);
    return 0;   
} 

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

int main() {
    ll n, d, a;
    cin >> n >> d >> a;
    vector<pair<ll, ll>> xh(n);
    rep(i, n) cin >> xh[i].first >> xh[i].second;
    sort(xh.begin(), xh.end());

    ll ans = 0, running_sum = 0;
    queue<pair<ll, ll>> bombs;
    rep(i, n) {
        while (!bombs.empty() && bombs.front().first < xh[i].first) {
            running_sum -= bombs.front().second * a;
            bombs.pop();
        }
        xh[i].second = max(0ll, xh[i].second - running_sum);
        if (xh[i].second <= 0) continue;

        ll cur_til = xh[i].first + 2 * d;
        ll cur_ned = (xh[i].second + a - 1) / a;
        ans += cur_ned;
        running_sum += cur_ned * a;
        bombs.push({cur_til, cur_ned});
    }
    cout << ans << endl;
}

Measured memory_bytes: 4992
from collections import deque

dx,dy = [1, 0, -1, 0], [0, 1, 0, -1]

H, W = map(int, input().split())
seen = [[False]*W for _ in range(H)]
c,S = 0,[]
for _ in range(H):
	S.append(input())

for i in range(H):
	for j in range(W):
		if (S[i][j]=='#') and (not seen[i][j]):
			d = deque()
			d.append((i, j))
			seen[i][j],b,w = True,1,0
			while d:
				px,py = d.popleft()
				for x,y in zip(dx,dy):
					nx, ny = px+x, py+y
					if nx < 0 or ny < 0 or nx >= H or ny >= W or seen[nx][ny]:
						continue
					if S[px][py]=='#' and S[nx][ny] == '.':
						d.append((nx, ny))
						seen[nx][ny] = 1
						w += 1
					elif S[px][py]=='.' and S[nx][ny] == '#':
						d.append((nx, ny))
						seen[nx][ny] = 1
						b += 1
			c += b*w

print(c)

Measured memory_bytes: 78016
#pragma GCC optimize ("O2")
#pragma GCC target ("avx2")
#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) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const ll mod = 100000000000000003;
int ne[200001], he[100001];
char C[1200100];

ll num[524300];
int kazu[524300];
const int ma = (1 << 19) - 1;
int query(ll n) {
	int n2 = (n & ma) + 1;
	while (num[n2]) {
		if (num[n2] == n + 1) return kazu[n2];
		n2 = n2 * 61 % 524287;
	}
	return 0;
}
void add(ll n, int b) {
	int n2 = (n & ma) + 1;
	while (num[n2]) {
		if (num[n2] == n + 1) {
			kazu[n2] |= b;
			return;
		}
		n2 = n2 * 61 % 524287;
	}
	num[n2] = n + 1;
	kazu[n2] = b;
}

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


	fread(C, 1, 1200100, stdin);
	char* ci = C, c;
	int N = 0;
	while ((c = *ci++) >= '0') N = N * 10 + c - '0';
	set<pair<int, char*>> ST;
	char* s[200001];
	rep1(i, N) {
		s[i] = ci;
		while (*ci++ >= '0');
		int n = ci - s[i] - 1;	
		if (n <= 100000) {
			ne[i] = he[n];
			he[n] = i;
		}
		else {
			ST.insert(mp(n, s[i]));
		}
	}

	ll kotae = 0;

	for (int M = 1; M <= 100000; M++) {
		for (int p = he[M]; p; p = ne[p]) {
			auto S = s[p];
			int k[26] = {};
			ll are = 0;
			for (int i = M - 1; i >= 1; i--) {
				int tmp = query(are);
				rep(j, 26) if ((tmp >> j & 1)) {
					k[j]++;
				}
				kotae += k[S[i] - 'a'];
				k[S[i] - 'a'] = 0;
				are = (are * 30 + S[i] - 'a' + 1) % mod;
			}

			kotae += k[S[0] - 'a'];
			k[S[0] - 'a'] = 0;

			add(are, 1 << (S[0] - 'a'));
		}
	}
	for (auto p : ST) {
		auto S = p.second;
		int k[26] = {};
		ll are = 0;
		for (int i = p.first - 1; i >= 1; i--) {
			int tmp = query(are);
			rep(j, 26) if ((tmp >> j & 1)) {
				k[j]++;
			}
			kotae += k[S[i] - 'a'];
			k[S[i] - 'a'] = 0;
			are = (are * 30 + S[i] - 'a' + 1) % mod;
		}

		kotae += k[S[0] - 'a'];
		k[S[0] - 'a'] = 0;

		add(are, 1 << (S[0] - 'a'));
	}
	co(kotae);


	Would you please return 0;
}

Measured memory_bytes: 13192