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

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

const int mod = 1000000007;

int main() {
	int n;
	cin >> n;
	vector<int> a(n);
	ll sum = 0LL;
	rep(i, n) {
		cin >> a[i];
		sum += (ll)a[i];
	}

	if (n == 1) {
		cout << 0 << endl;
		return 0;
	}

	double ave = (double)sum / n;

	vector<double> b(n);

	rep(i, n) {
		b[i] = abs(ave - (double)a[i]);
	}

	double mi = 1e9;
	int num = (int)1e9;

	rep(i, n) {
		if (mi >= b[i]) {
			if (mi == b[i]) {
				if (num > i) num = i;
			}
			else {
				num = i;
				mi = b[i];
			}
		}
	}

	cout << num << endl;
	return 0;
}

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

typedef long long ll;
#define endl '\n'
template <typename t> bool ckmin(t& a, const t& b) {return a > b ? a = b, true : false;}

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

    ll n, k;
    cin >> n >> k;
    n = n % k;
    ll m = n;
    while(n > abs(n - k)) {
        n = abs(n - k);
        ckmin(m, n);
    }
    cout << m << endl;
}




Measured memory_bytes: 256
import sys, io, os, re
import bisect
from pprint import pprint
from math import sin, cos, pi, radians, sqrt, floor, ceil
from copy import copy, deepcopy
from collections import deque, defaultdict
from fractions import gcd
from functools import reduce

def array1(n): return [0] * n
def array2(n, m): return [[0] * m for x in range(n)]
def array3(n, m, l): return [[[0] * l for y in xrange(m)] for x in xrange(n)]

n1 = lambda: int(sys.stdin.readline().strip())
nn = lambda: list(map(int, sys.stdin.readline().strip().split()))
f1 = lambda: float(sys.stdin.readline().strip())
fn = lambda: list(map(float, sys.stdin.readline().strip().split()))
s1 = lambda: sys.stdin.readline().strip()
sn = lambda: list(sys.stdin.readline().strip().split())
nl = lambda n: [n1() for _ in range(n)]
fl = lambda n: [f1() for _ in range(n)]
sl = lambda n: [s1() for _ in range(n)]
nm = lambda n: [nn() for _ in range(n)]
fm = lambda n: [fn() for _ in range(n)]
sm = lambda n: [sn() for _ in range(n)]

mod = 1000000007

N = n1()
(A, B) = ([], [])
for i in range(N):
    a, b = nn()
    g = gcd(a, b)
    if g != 0: a //= g; b //=g
    A.append(a)
    B.append(b)

d = defaultdict(int)
for i in range(N):
    d[(A[i], B[i])] += 1

ans = 1
n = 0
if (0, 0) in d:
    n = d.pop((0, 0))

while len(d) > 0:
    #print(d, ans)
    (x, y), n1 = d.popitem()
    if y < 0: x *= -1; y *= -1

    n2 = 0
    if (y, -x) in d: n2 += d.pop((y, -x))
    if (-y, x) in d: n2 += d.pop((-y, x))

    ans = (ans * ((pow(2,n1,mod) -1 + pow(2,n2,mod) - 1) % mod + 1)) % mod

print((ans-1+n)%mod)

Measured memory_bytes: 162740
import java.util.*;
 
public class Main {
	
    public static void main(String[] args) {
    	Scanner sc = new Scanner(System.in);
    	int N = sc.nextInt();
    	List<Integer> list = new LinkedList<>();
    	int max = 0;
    	int order = 0;
    	for (int i = 0; i < N; i++) {
    		int num = sc.nextInt();
    		if (max < num) {
    			max = num;
    			order = i;
    		}
    		list.add(num);
    	}
    	Collections.sort(list);
    	int submax = list.get(list.size() - 2);
    	StringBuilder sb = new StringBuilder();
    	for (int i = 0; i < N; i++) {
    		if (i == order) {
    			sb.append(submax).append("\n");
    		} else {
    			sb.append(max).append("\n");
    		}
    	}
    	System.out.println(sb);
    }
}

Measured memory_bytes: 99752
#include <iostream>
#include <map>
using namespace std;
map<pair<int,int>,int> m;
int par[2][200005];
int find(int i,int x)
{
	if (par[i][x]!=x)
	par[i][x]=find(i,par[i][x]);
	return par[i][x];
}
void Union(int i,int x,int y)
{
	x=find(i,x);
	y=find(i,y);
	if (x!=y)
	par[i][x]=y;
}
int main()
{
	int n,k,l;
	scanf("%d%d%d",&n,&k,&l);
	for (int i=1;i<=n;i++)
	{
		par[0][i]=i;
		par[1][i]=i;
	}
	while (k--)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		Union(0,a,b);
	}
	while (l--)
	{
		int a,b;
		scanf("%d%d",&a,&b);
		Union(1,a,b);
	}
	for (int i=1;i<=n;i++)
	m[{find(0,i),find(1,i)}]++;
	for (int i=1;i<=n;i++)
	printf("%d ",m[{find(0,i),find(1,i)}]);
}

Measured memory_bytes: 13568
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int prime_decision(int x)
{
    int flag = 1;
    int max_i = (int)sqrt(x) + 1;

    if (x == 2)
    {
        return flag;
    }

    for (int i = 2; i <= max_i; i++)
    {
        if (x % i == 0)
        {
            flag = 0;
            return flag;
        }
    }
    return flag;
}

int main(void)
{
    int n;
    int A[10000];
    int cnt = 0;

    scanf("%d", &n);
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &A[i]);
    }

    for (int i = 0; i < n; i++)
    {
        cnt += prime_decision(A[i]);
    }

    printf("%d\n", cnt);

    return 0;
}


Measured memory_bytes: 2112
a = int(input())
b = [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(b[a-1])


Measured memory_bytes: 2940
import sys

sys.setrecursionlimit(5005)
SENTINEL = 10 ** 13

n = int(input())
aaa = list(map(int, input().split()))
links = [set() for _ in [0] * n]
for line in sys.stdin.readlines():
    u, v = map(int, line.split())
    u -= 1
    v -= 1
    links[u].add(v)
    links[v].add(u)


def dfs(v, p):
    a = aaa[v]
    ret1 = [a]
    ret2 = [a]
    if a < 0:
        ret1[0] = SENTINEL

    for u in links[v]:
        if u == p:
            continue
        res1, res2 = dfs(u, v)
        new1 = [SENTINEL] * (len(ret1) + len(res1))
        new2 = [SENTINEL] * (len(ret2) + len(res2))
        for i, t in enumerate(ret1):
            for j, s in enumerate(res1):
                new1[i + j] = min(new1[i + j], t + s)
                if s < SENTINEL:
                    new1[i + j + 1] = min(new1[i + j + 1], t)
            for j, s in enumerate(res2):
                new2[i + j] = min(new2[i + j], t + s)
                if s < 0:
                    new1[i + j + 1] = min(new1[i + j + 1], t)
        for i, t in enumerate(ret2):
            for j, s in enumerate(res1):
                new2[i + j] = min(new2[i + j], t + s)
                if s < SENTINEL:
                    new2[i + j + 1] = min(new2[i + j + 1], t)
            for j, s in enumerate(res2):
                new2[i + j] = min(new2[i + j], t + s)
                if s < 0:
                    new2[i + j + 1] = min(new2[i + j + 1], t)

        # print(' ', '1', p, v, u, ret1, res1, new1)
        # print(' ', '2', p, v, u, ret2, res2, new2)
        ret1, ret2 = new1, new2

    return ret1, ret2


res1, res2 = dfs(0, -1)
ans1, ans2 = 0, 0
for ans1, s in enumerate(res1):
    if s < SENTINEL:
        break
for ans2, s in enumerate(res2):
    if s < 0:
        break
print(min(ans1, ans2))


Measured memory_bytes: 198532
// Kyoto University Programming Contest 2016
// C - クッキー☆増殖装置 / Cookie Breeding Machine

#include <cstdio>
using namespace std;


int T, N, D;
int ans;

int main() {

  for (scanf("%d", &T); T > 0; T--) {
    scanf("%d%d", &N, &D);
    ans = (N - 1) * 127;
    ans += (N % 2 == 0) ? 127 - D : D;
    printf("%d\n", ans);
  }

  return 0;

}




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


int main() {

  string S;
  cin>>S;

  bool flag=false;
  
  if(S.size()%2==0){
  for(int i=0;i<S.size()-1;i+=2){
    if(S.at(i)=='h'&&S.at(i+1)=='i')
      flag=true;
    else{
      flag=false;
      break;
    }
  }
  }
  
  if(flag)
    cout<<"Yes"<<endl;
  else
    cout<<"No"<<endl;
  
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using llong = long long;
using ldouble = long double;

void fnInput(int& rnWide, int& rnHigh, int& rnx, int& rny)
{
  cin >> rnWide >> rnHigh >> rnx >> rny;
}

void fnRectCutArea(int nWide, int nHigh, int nx, int ny)
{
  llong nRectArea = (llong)nWide * nHigh;
  ldouble nRectCutArea = nRectArea / 2.0;
  cout << setprecision(18) << nRectCutArea << " ";

  double nCenterx = nWide / 2.0;
  double nCentery = nHigh / 2.0;
  if (nCenterx == nx && nCentery == ny)
    cout << "1" << endl;
  else
    cout << "0" << endl;
}
  
int main()
{
  int nWide, nHigh, nx, ny;

  fnInput(nWide, nHigh, nx, ny);
  fnRectCutArea(nWide, nHigh, nx, ny);

  return 0;
}

Measured memory_bytes: 3816
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll MOD = 1e9 + 7;
const ll INF = LLONG_MAX;
const ll MINF = LLONG_MIN;
const int INT_INF = INT_MAX;

int main()
{
    string s;
    cin >> s;
    for (int i = 0; i < 3; i++)
    {
        cout << s[i];
    }
    cout << endl;
}

Measured memory_bytes: 3620
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<utility>
#include<map>
#include<set>
#include <sstream>
#include<queue>
#include<stack>
#include<functional>
#include<math.h>
#include <iomanip>
using namespace std;


int main(void){
    char c;
    cin >> c;
    if(c <= 'Z'){
        cout << 'A' << endl;
    }else{
        cout << 'a' << endl;
    }
    return 0;
}

Measured memory_bytes: 3628
n=int(input())
l=[]
for i in range(n):
  x,y=map(int,input().split())
  l.append([x-y,x+y])
count=0
l=sorted(l)
l=l[::-1]
count+=1
now=l[0][0]
for i in range(1,n):
  if now>=l[i][1]:
    now=l[i][0]
    count+=1
  else:
    pass
print(count)


Measured memory_bytes: 20896
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            String[] input = Console.ReadLine().Split();
            long a = long.Parse(input[0]);
            long b = long.Parse(input[1]);
            long c = long.Parse(input[2]);
            long k = long.Parse(input[3]);

            if (k % 2 == 0)
            {
                Console.Write(a - b);
            }
            else
            {
                Console.Write(b - a);
            }

        }
    }
}


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

vector<bool> vis;
vector<int> dis;
vector<int> adj[205];
bool flag = true;

void dfs(int now) {
	for (auto x : adj[now]) {
		if (vis[x] and (dis[x] & 1) == (dis[now] & 1)) {
			flag = false;
		}
		if (!vis[x]) {
			vis[x] = true;
			dis[x] = dis[now] + 1;
			dfs(x);
		}
	}
}

int main() {
	int n, maxV;
	cin >> n;
	
	vector<string> mat(n);
	vector<vector<int>> floyd(n, vector<int>(n, 1000));
	for (int i = 0; i < n; ++i) {
		cin >> mat[i];
		for (int j = 0; j < n; ++j) {
			if (mat[i][j] == '1') {
				adj[i].push_back(j);
				floyd[i][j] = 1;
			}
			if (i == j) {
				floyd[i][j] = 0;
				// printf("floyd[%d][%d]: %d\n", i, j, floyd[i][j]);
			}
		}
	}
	
	/// [GUESS]:
	/// 	if the Graph doesn't contains any cycle with odd length, 
	/// 	the answer will be the Graph's Diameter (Use Floyd to get the Diameter)
	
	dis.assign(n, 1);
	vis.assign(n, false);
	vis[0] = true;
	dfs(0);
	
	if (!flag) {
		cout << -1 << "\n";
		return 0;
	}
	
	for (int x = 0; x < n; ++x) {
		for (int i = 0; i < n; ++i) {
			for (int j = 0; j < n; ++j) {
				floyd[i][j] = min(floyd[i][j], floyd[i][x] + floyd[x][j]);
			}
		}
	}
	
	int maxDis = 0;
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			// printf("floyd[%d][%d]: %d\n", i, j, floyd[i][j]);
			maxDis = max(maxDis, floyd[i][j]);
		}
	}
	
	cout << maxDis + 1 << "\n";
	
	return 0;
}

Measured memory_bytes: 768
package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	num, _ := strconv.Atoi(scanString())
	return num
}

func scanString() string {
	sc.Scan()
	return sc.Text()
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	l := float64(scanInt())
	x := l / 3.0
	diff := l - 3*x
	fmt.Println((x + diff) * x * x)
}


Measured memory_bytes: 640
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<cmath>
#include<iomanip>
#include<functional>
using namespace std;

int INF = 1e9 + 7;

typedef long long ll;
typedef pair<int, int> P;

int main() {
	int n;
	cin >> n;
	vector<int> coin = { 1, 6, 9, 36, 81, 216, 729, 1296, 6561, 7776, 46656, 59049 };
	vector<int> dp(100010, INF);
	dp[0] = 0;
	for (int i = 0; i <= 11; ++i) {
		for (int j = 0; j + coin[i] <= n; j++) {
			dp[j + coin[i]] = min(dp[j + coin[i]], dp[j] + 1);
		}
	}
	cout << dp[n] << endl;
}

Measured memory_bytes: 640
#pragma GCC optimize("Ofast")
#pragma GCC optimization ("O3")
#pragma GCC optimize ("unroll-loops")
#pragma GCC target("avx,avx2,fma")
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define p 1000000007
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<long long,long long>
#define LONGLONG_MAX 10000000000000000
using namespace std;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	long long r,d,x;
	cin>>r>>d>>x;
	for(int i=0;i<10;i++){
		x=r*x-d;
		cout<<x<<endl;
	}	
	    return 0;
}

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

int n, m, k, s;
std::vector<std::vector<int>> vec;
std::vector<int> p;


int main() {
    std::cin >> n >> m;
    for (int i = 0; i < m; i++) {
        std::cin >> k;
        std::vector<int> vec2;
        for (int j = 0; j < k; j++) {
            std::cin >> s;
            vec2.push_back(s-1);
        }
        vec.push_back(vec2);
    }
    p.assign(m, 0);
    for (int i = 0; i < m; i++) {
        std::cin >> p[i];
    }
    
    int ans = 0;
    int e = std::pow(2, n);
    for (int i = 0; i < e; i++) {
        bool ok = true;
        for (int j = 0; j < m; j++) {
            int c = 0;
            for (int k = 0; k < vec[j].size(); k++) {
                if ((i >> vec[j][k]) & 1) {
                    c++;
                }
            }
            if (c%2 != p[j]) {
                ok = false;
                break;
            }
        }
        if (ok) {
            ans++;
        }
    }
    std::cout << ans << std::endl;
}


Measured memory_bytes: 640
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
 
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
V = LIST()
V.sort()
a = V[0]
for i in range(N-1):
    a = (a + V[i+1]) / 2
print(a)


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

int main(){
  int n,k;
  cin >> n >> k;
  string s;
  cin >> s;
  if(s[k-1]=='A')s[k-1]='a';
  if(s[k-1]=='B')s[k-1]='b';
  if(s[k-1]=='C')s[k-1]='c';
  cout << s << endl;
}


Measured memory_bytes: 256
use std::io;
use std::collections::HashMap;

fn main() {
    let mut s = String::new();

    io::stdin().read_line(&mut s)
        .unwrap();

    let mut dist = HashMap::new();


    for c in s.trim().chars() {
        let count = dist.entry(c).or_insert(0);
        *count += 1;
    }

    if dist.len() == 2 && dist.values().all(|x| *x == 2) {
        println!("Yes");
    } else {
        println!("No");
    }
}


Measured memory_bytes: 4352
import sys
input = sys.stdin.readline

n = int(input())

task_list = []

for i in range(n):
    a, b = [ int(v) for v in input().split() ]
    task_list.append([b,a])
task_list = sorted(task_list)

s = 0
for i in range(n):
    s += task_list[i][1]
    task_list[i][1] = s

task_list = [ i[0] >= i[1] for i in task_list ]

if all(task_list):
    ans = "Yes"
else:
    ans = "No"
    
print(ans)


Measured memory_bytes: 86748
# coding: utf-8

N = int(input())
X = list(map(int,input().split()))
judge = float('inf')
for i in range(1,101):
    p = i
    tmp = 0
    for j in range(N):
        tmp += (X[j]-p)**2
    if tmp < judge:
        judge = tmp
        ans = tmp
        
print(ans)

Measured memory_bytes: 3064
#include<bits/stdc++.h>
using namespace std;
int main(){
 long n;
  cin>>n;long a,b;
  vector<pair<long,long>>v;
  for(int i=0;i<n;i++){
  cin>>a>>b;
    v.push_back({b,a});

  }
  sort(v.begin(),v.end());
  int flg=0;
  long t=0;
  for(long i=0;i<n;i++)
      {
      a=v[i].first;
      b=v[i].second;
    t+=b;
    if(t<=a){
    continue;
    }

    flg=1;
    break;

      }

      if(flg==0){
      cout<<"Yes"<<endl;
      }
      else{
        cout<<"No"<<endl;
      }
      }


Measured memory_bytes: 6512
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

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

    static class CWalkingTakahashi {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long x = in.readLong(), k = in.readLong(), d = in.readLong();
            if (x < 0)
                x *= -1;
            long req = x / d;

            if (k <= req)
                x -= k * d; // this is the closest we can get to zero
            else {
                k -= req; // reach the closest to zero and exhaust the remaining moves by revolving
                if (k % 2 == 0)
                    x -= d * req;
                else
                    x -= d * (req + 1);
            }

            if (x < 0)
                x *= -1;

            System.out.println(x);

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new RuntimeException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new RuntimeException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public long readLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}



Measured memory_bytes: 32468
S = input()

A = int(S[:2])
B = int(S[2:])

def isMonth(i) :
    if i >= 1 and i <= 12 :
        return True
    else :
        return False

if isMonth(A) and isMonth(B) :
    print('AMBIGUOUS')
elif not isMonth(A) and isMonth(B) :
    print('YYMM')
elif isMonth(A) and not isMonth(B) :
    print('MMYY')
else :
    print('NA')

Measured memory_bytes: 3060
import java.util.*;
public class Main{
 public static void main(String[] args){
   Scanner sc = new Scanner(System.in);
   int N = sc.nextInt();
   
   int[] ai = new int[N];
   for(int i=0;i<N;i++) ai[i]=sc.nextInt();

   int count =0;
  
   for(int k = 0;k<N;k++)
   {
     for(int i = 0;i<30;i++)
     {
       if(ai[k]%2==0)
       {
          ai[k] /=2;
          count++;
       }
       else break;
     }
   }
   

   System.out.println(count);
 }
}

Measured memory_bytes: 33780
//Nayeem Shahriar Joy ,Applied Physics And Electronic Engineering , University of Rajshahi.


#include <bits/stdc++.h>
#include<algorithm>
#include<cstring>
#include<string>

using namespace std;

int main()

{

  ios_base::sync_with_stdio(false);

  cin.tie(NULL);

  int T,n,x,b,w;

  char s;

  cin>>w;

  int a[w];

  for(int i=0;i<w;i++)

  {
      a[i]=i+1;
  }

  cin>>n;

  while(n--)

  {
      cin>>x>>s>>b;

      swap(a[x-1],a[b-1]);

  }

   for(int i=0;i<w;i++)

   {
       cout<<a[i]<<endl;
   }


  return 0;

}

Measured memory_bytes: 3060
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
ll n, a[100100], ans;
int main(void){
    // Your code here!
    cin >> n;
    for (ll i = 0; i < n; i++) cin >> a[i];
    sort(a, a + n);
    if (n % 2){
        ll zan = 0;
        zan += a[n / 2] + a[n / 2 + 1];
        for (ll i = 0; i <= n / 2 - 1; i++) zan -= a[i] * 2;
        for (ll i = n / 2 + 2; i < n; i++) zan += a[i] * 2;
        ans -= (a[n / 2] + a[n / 2 - 1]);
        for (ll i = 0; i <= n / 2 - 2; i++) ans -= a[i] * 2;
        for (ll i = n / 2 + 1; i < n; i++) ans += a[i] * 2;
        ans = max(ans, zan);
    } else {
        ans += a[n / 2] - a[n / 2 - 1];
        for (ll i = 0; i < n / 2 - 1; i++) ans -= a[i] * 2;
        for (ll i = n / 2 + 1; i < n; i++) ans += a[i] * 2;
    }
    cout << ans << endl;
}


Measured memory_bytes: 1024
#include<bits/stdc++.h>
using namespace std;
 
#define ff              first
#define fo(i,n)         for(i=0;i<n;i++)
#define Fo(i,k,n)       for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define deb(x)          cout << #x << "=" << x << endl
#define deb2(x, y)      cout << #x << "=" << x << "," << #y << "=" << y << endl
#define ss              second
#define int             long long
#define pb              push_back
#define mp              make_pair
#define pii             pair<int,int>
#define vi              vector<int>
#define mii             map<int,int>
#define pqb             priority_queue<int>
#define pqs             priority_queue<int,vi,greater<int> >
#define setbits(x)      __builtin_popcountll(x)
#define zrobits(x)      __builtin_ctzll(x)
#define mod             1000000007
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define w(x)            int x; cin>>x; while(x--)
#define FIO             ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
mt19937                 rng(chrono::steady_clock::now().time_since_epoch().count());
 
 
const int N = 3e5, M = N;
//=======================
 
 
void solve() {
	int n;
	cin>>n;
	int d1[n],d2[n];
	int i;
	fo(i,n)
		cin>>d1[i]>>d2[i];
	int cnt =0;
	fo(i,n){
		if(d1[i]==d2[i])cnt++;
		else{
			if(cnt>=3){cout<<"Yes";return;}
			else cnt=0;
		}
	}
	if(cnt>=3)cout<<"Yes";
	else cout<<"No";
}
 
int32_t main()
{
  FIO;
#ifndef ONLINE_JUDGE
  freopen("input.txt", "r", stdin);
  freopen("output.txt", "w", stdout);
#endif
  solve();
  return 0;
}

Measured memory_bytes: 3640
#include <bits/stdc++.h>
typedef long long int ll;
typedef long double ld;
#define pb push_back
#define pii pair < ll , ll >
#define F first
#define S second
#define int long long
#define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")
using namespace std;
/// khodaya komak kon
/// ya navid navid
const int N=2e5+100;

ll a[N];
int32_t main(){
    ll n;
    cin >> n;
    if (n%2==1){
        cout << 0 << endl;
        return 0;
    }
    ll ans=0;
    ll cnt=2;
    while (cnt*5<=(ll)1000000000000000000){
        cnt*=5;
        if (cnt%(ll)2==1){
            continue;
        }
        ans+=n/cnt;
    }
    cout << ans;
}


Measured memory_bytes: 256
n=int(input())
c=[0 for i in range(n-1)]
s=[0 for i in range(n-1)]
f=[0 for i in range(n-1)]
for i in range(n-1):
    c[i],s[i],f[i]=map(int,input().split())
ans=[0 for i in range(n)]
for i in range(n-1):
    po=i
    while(po<n-1):
        if(s[po]>ans[i]):
            ans[i]=s[po]
            ans[i]+=c[po]
            po+=1
        else:
            ans[i]+=f[po]-1-((ans[i]+f[po]-1)%f[po])+c[po]
            po+=1
for i in ans:
    print(i)


Measured memory_bytes: 3188
#include <stdio.h>

int main()
{
	int n,total[2],in[2];

	while( scanf("%d",&n) && n ){
		total[0] = 0; total[1] = 0;
		for(int i = 0; i < n; i++){
			scanf("%d %d",&in[0],&in[1]);
			if(in[0] > in[1]){
				total[0] += in[0]+in[1];
			}
			else if(in[1] > in[0]){
				total[1] += in[0]+in[1];
			}
			else{
				total[0] += in[0];
				total[1] += in[1];
			}
		}
		printf("%d %d\n",total[0],total[1]);
	}

	return 0;
}

Measured memory_bytes: 1028
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	var N int
	scanner.Scan()
	fmt.Sscanf(scanner.Text(), "%d", &N)

	cnt := 0
	for p := 11; cnt < N; p = p + 10 {
		if isPrime(p) {
			fmt.Print(p, " ")
			cnt++
		}
	}
	fmt.Println()
}

func isPrime(value int) bool {
	for i := 2; i*i <= value; i++ {
		if value%i == 0 {
			return false
		}
	}
	return value > 1
}


Measured memory_bytes: 640
#include<iostream>

using namespace std;

int main() {
  int a1,a2,b1,b2;
  cin>>a1>>a2>>b1>>b2;

  if(a2<b1||b2<a1) cout<<0<<endl;
  else{
      if(a1<=b1){
          if(a2<=b2) cout<<a2-b1<<endl;
          else cout<<b2-b1<<endl;
      }
      else{
          if(a2<=b2) cout<<a2-a1<<endl;
          else cout<<b2-a1<<endl;
      }
  }
  
  return 0;
}

Measured memory_bytes: 256
ans = 0
n = int(input())
s = input()

for x in range(10):
    if s.find(str(x)) > -1:
        tmp = s[s.find(str(x)) + 1:]
        for y in range(10):
            if tmp.find(str(y)) > -1:
                tmp2 = tmp[tmp.find(str(y)) + 1:]
                for z in range(10):
                    if tmp2.find(str(z)) > -1:
                        ans += 1

print(ans)


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

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

    if(A%2 != B%2)
        cout << "IMPOSSIBLE" << endl;
    else{
        long long K = (A + B) / 2;
        cout << K << endl;
    }
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
	 int n;
	 cin>>n;
	 vector<int>arr(n,0);
	 int temp;
	 for(int i=0;i<n;i++)
	 {
	 	cin>>temp;
	 	arr[i]=temp;
	 }
	 int ans=0;
	 for(int i=0;i<n;i++)
	 {
	 	if(arr[i]%2!=0&&(i+1)%2!=0)
	 	ans++;
	 }
	 cout<<ans;
			
		
		   
}

			
			
           
    



   



Measured memory_bytes: 3652
//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
#include <ctime>


using namespace std;

//conversion
//------------------------------------------
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v; }
template<class T> inline string toString(T x) { ostringstream sout; sout << x; return sout.str(); }

//math
//-------------------------------------------
template<class T> inline T sqr(T x) { return x*x; }

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define EXISTch(s,c) ((((s).find_first_of(c)) != std::string::npos)? 1 : 0)//cがあれば1 if(1)
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n)  FOR(i,0,n)
#define loop(n) FOR(i,0,n)
#define rrep(i,a,b) for(int i=(a);i>=(b);--i)
//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI = acos(-1.0);
const int INF = (int)1000000007;
const LL MOD = (LL)1000000007;//10^9+7
const LL INF2 = (LL)100000000000000000;//10^18

char convert(char c) {
	if (c >= 'a'&&c <= 'z') {
		return c - 'a' + 'A';
	}else if (c >= 'A'&&c <= 'Z') {
		return c - 'A' + 'a';
	}
	else {
		return c;
	}
}

int main() {
	string s;
	getline(cin, s);

	for (char c : s) {
		cout << convert(c);
	}

	cout<<endl;
	return 0;
}


Measured memory_bytes: 3144
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
#define equals(a, b) (fabs((a) - (b)) < EPS)
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const ll mod2 = 998244353;
const ll INF = 1e18;
const long double EPS = 1e-10;

int main() {
  int a, b;
  string s;
  cin >> a >> b >> s;

  rep(i, a + b + 1) {
    if (i == a && s[i] != '-') {
      cout << "No" << endl;
      return 0;
    }
    else if (i != a && s[i] == '-') {
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;


  
  return 0;
}

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

using namespace std;

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

int main() {
  int N;
  cin >> N;
  vector<int> mochis(N);
  rep(i, N){
    cin >> mochis.at(i);
  }
  
  sort(mochis.begin(), mochis.end(), greater<int>());
  
  int c = 1;
  rep(i, N){
    int tmp = mochis.at(i);
    for(int j=i+1; j<N; j++){
      if(tmp == mochis.at(j))
        continue;
      else {
        i = j - 1;
        c++;
        break;
      } 
    }
  }
  cout << c << endl;
}

Measured memory_bytes: 256
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		long hp=sc.nextLong();
		long sum = 0;
		long t = 1;
		while(hp>0) {
			hp/=2;
			sum+=t;
			t+=t;
		}
		System.out.print(sum);
	}
}


Measured memory_bytes: 22996
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  int n,a,b;
  int s=0;
  cin >> n;
  for(int i=0;i<n;i++){
    cin >> a >> b;
    int c= b-a+1;
    s+=c;
  }
  cout << s << endl;
 
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> P;
typedef pair<ll, ll> Pll;
#define debug(var)  do{std::cout << #var << " : ";view(var);}while(0)
template<typename T> void view(T e){std::cout << e << std::endl;}
template<typename T> void view(const std::vector<T>& v){for(const auto& e : v){ std::cout << e << " "; } std::cout << std::endl;}
template<typename T> void view(const std::vector<std::vector<T> >& vv){ for(const auto& v : vv){ view(v); } }
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

const int MOD = 1000000007;
const int INF = 1e9;

const int mod = 1000000007;
const int inf = 1e9;
#define PI acos(-1);
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int ddx[8] = {1,1,1,-1,-1,-1,0,0};
int ddy[8] = {0,1,-1,0,1,-1,1,-1};


int main(){
    int a, b;
    cin >> a >> b;
    cout << max(0, a-b) << endl;
}

Measured memory_bytes: 256
while True:
    H, W = map(int, input().split())
    if H == W == 0:
        break
    str = "#." * (W // 2 + 1)
    for i in range(H):
        if i % 2 == 0:
            print(str[:W:])
        else:
            print(str[1:W + 1:])
    print()


Measured memory_bytes: 5608
import sys
def main():
    input = sys.stdin.readline
    H, W = map(int, input().split())
    A = [list(input().rstrip()) for _ in range(H)]
    cnt = sum([1 if A[i][j]=='#' else 0 for i in range(H) for j in range(W)])

    ans = False
    stack = [(0, 0, 1)]
    while stack:
        i, j, d = stack.pop()
        if i == H-1 and j == W-1:
            if d == cnt:
                ans = True
            break
        for di, dj in [(0,1), (1,0)]:
            ni, nj = i+di, j+dj
            if ni >= H or nj >= W: continue
            if A[ni][nj] != '#': continue
            stack.append((ni, nj, d+1))
    print('Possible' if ans else 'Impossible')

if __name__ == '__main__':
    main()

Measured memory_bytes: 38256
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
 
 public class Main {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
	    
		//inputs
		int n = input.nextInt();
		int m = input.nextInt();
		int sum = 0;
		for(int i = 0 ; i < m ; i++)
			sum += input.nextInt();
		
		System.out.println(n >= sum ? n - sum : -1);
	}
}

Measured memory_bytes: 39396
#![allow(non_snake_case)]
#![allow(dead_code)]
#![allow(unused_macros)]
#![allow(unused_imports)]

use std::str::FromStr;
use std::io::*;
use std::collections::*;
use std::cmp::*;

struct Scanner<I: Iterator<Item = char>> {
    iter: std::iter::Peekable<I>,
}

macro_rules! exit {
    () => {{
        exit!(0)
    }};
    ($code:expr) => {{
        if cfg!(local) {
            writeln!(std::io::stderr(), "===== Terminated =====")
                .expect("failed printing to stderr");
        }
        std::process::exit($code);
    }}
}

impl<I: Iterator<Item = char>> Scanner<I> {
    pub fn new(iter: I) -> Scanner<I> {
        Scanner {
            iter: iter.peekable(),
        }
    }

    pub fn safe_get_token(&mut self) -> Option<String> {
        let token = self.iter
            .by_ref()
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        if token.is_empty() {
            None
        } else {
            Some(token)
        }
    }

    pub fn token(&mut self) -> String {
        self.safe_get_token().unwrap_or_else(|| exit!())
    }

    pub fn get<T: FromStr>(&mut self) -> T {
        self.token().parse::<T>().unwrap_or_else(|_| exit!())
    }

    pub fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
        (0..len).map(|_| self.get()).collect()
    }

    pub fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
        (0..row).map(|_| self.vec(col)).collect()
    }

    pub fn char(&mut self) -> char {
        self.iter.next().unwrap_or_else(|| exit!())
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.get::<String>().chars().collect()
    }

    pub fn line(&mut self) -> String {
        if self.peek().is_some() {
            self.iter
                .by_ref()
                .take_while(|&c| !(c == '\n' || c == '\r'))
                .collect::<String>()
        } else {
            exit!();
        }
    }

    pub fn peek(&mut self) -> Option<&char> {
        self.iter.peek()
    }
}

trait Joinable {
    fn join(self, sep: &str) -> String;
}

impl<U: ToString, T: Iterator<Item = U>> Joinable for T {
    fn join(self, sep: &str) -> String {
        self.map(|x| x.to_string()).collect::<Vec<_>>().join(sep)
    }
}

struct Env {
    N: usize,
}

struct Solver {
    res: Vec<String>,
}

impl Solver {
    fn new() -> Solver {
        Solver { res: Vec::new() }
    }
    fn dfs(&mut self, e: &Env, i: usize, maxc: u8, acc: &mut Vec<char>) {
        if i == e.N {
            self.res.push(acc.iter().map(|&i| i).collect());
            return;
        }
        for ci in b'a'..maxc+2 {
            acc.push(ci as char);
            self.dfs(e, i+1, max(maxc, ci), acc);
            acc.pop();
        }
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin.bytes().map(|c| c.unwrap() as char));
    let N: usize = sc.get();
    let e = Env { N: N };
    let mut s = Solver::new();
    s.dfs(&e, 1, b'a', &mut vec!['a']);
    for i in s.res {
        println!("{}", i);
    }
}


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

#define fastio 			ios::sync_with_stdio(0);	cin.tie(0); cout.tie(0);  cout<<fixed;  cout<<setprecision(12);	
#define randomINT 		mt19937 rnd(chrono::steady_clock::now().time_since_epoch().count());
#define	newl 			cout<<"\n"
#define DISP(as)		for(auto it : as) cout<<it<<" ";newl;
#define all(x)         	(x).begin(),(x).end()
#define mset(x,val)    	memset(x,val,sizeof(x))
#define newl           	cout<<"\n"
#define pb             	push_back
#define mp             	make_pair
#define f 				first
#define s 				second
#define dline          cerr<<"///REACHED///\n";
#define deb1(x)        cerr<<#x<<" = "<<x<<'\n';
#define deb2(x,y)      cerr<<'['<<#x<<','<<#y<<"] = "<<'['<<x<<','<<y<<']'<<'\n';
#define deb3(x,y,z)    cerr<<'['<<#x<<','<<#y<<','<<#z<<"] = "<<'['<<x<<','<<y<<','<<z<<']'<<'\n';

typedef long long 				ll;
typedef long double 			ld;
typedef vector<ll> 				vll;
typedef pair<ll ,ll> 			pll;
typedef pair<ld,ld> 			pld;
typedef unordered_map<ll,ll> 	um;
typedef vector<pll> 			vpll;

const ll 	MAX5 	= 	1e+5+7;
const ll 	MAX7 	= 	1e+7+7;
const ll 	MAXN 	= 	MAX7;
const ll   	INF   	=  	0x7f7f7f7f7f7f7f7f;
const ll  	INFi 	=  	0x7f7f7f7f;
const ll 	MOD		=  	1e+9+7;

/*vll adj[MAXN];ll visit[MAXN]={};
ll dx8[]={0,1,1,1,0,-1,-1,-1}, dy8[]={1,1,0,-1,-1,-1,0,1};
ll dx4[]={0,1,0,-1}, dy4[]={1,0,-1,0};
*/
// <------------- Declare Variables Here ------------> //

ll T=1;
ll n,x,y,m;
string s,t;
//vll a,b;
// <------------- Implement Functions Here ----------> //


// <------------- Start of main() -------------------> //

void MAIN() {
	cin >> n;
	multiset<ll> A;
	for(ll i=0;i<n;i++) {
		cin>>x;
		A.insert(x);
	}
	vll a = {A.begin(),A.end()};
	ll cou = 0;
	
	for(ll i=0;i<n;i++) {
		for(ll j=i+1;j<n;j++) {
			for(ll k=j+1;k<n;k++) {
				if(a[i]+a[j] > a[k] && a[i]!=a[j] && a[j]!=a[k]) cou++;
			}
		}
	}
	cout<<cou;
}

int main() {
	fastio;randomINT;
	//cin>>T;
	while(T--) {
		MAIN();
	}
	return 0;
}



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

int A[1000010];
int N, ans;

int main() {
	cin >> N;
	for (int i = 0; i < 1000003; i++) A[i] = 0;
	for ( int n = 0; n < N; n++) {
		int a,b;
		cin >> a >> b;
		A[a] += 1;
		A[b + 1] -= 1;
	}
	ans = 0;
	for (int i = 1; i < 1000002; i++) {
		A[i] += A[i - 1];
	}
	
	for (int i = 1; i < 1000002; i++) {
		if (i <= A[i + 1]) {
			ans = i;
		}
	}
	cout << ans << endl;
}


Measured memory_bytes: 7020
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
typedef long long ll;
int main(){
    int n,A[200001],B[200001];
    cin>>n;
    rep(i,n+1) cin>>A[i];
    rep(i,n) cin>>B[i];
    ll b=0;
    rep(i,n){
        if(B[i]<=A[i]) b+=B[i],A[i]-=B[i];
        else{
            B[i]-=A[i];
            b+=A[i];
            A[i]=0;
            if(B[i]<=A[i+1]) b+=B[i],A[i+1]-=B[i];
            else b+=A[i+1],A[i+1]=0;
        }
    }
    cout<<b;
}

Measured memory_bytes: 1152
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(k,i,n) for(ll i=k;i<n;++i)
int main(void){
    // Your code here!
    ll n;
    cin>>n;
    vector<ll>a(n);
    ll maxa=0;
    rep(0,i,n){
        cin>>a[i];
        maxa=max(a[i],maxa);
    }
    ll na=0,c=0;
    rep(0,i,n){
        if(a[i]!=maxa)na=max(a[i],na);
        else ++c;
    }
    rep(0,i,n){
        if(a[i]!=maxa){
            cout<<maxa<<endl;
        }else{
            if(c==1)cout<<na<<endl;
            else cout<<maxa<<endl;
        }
    }
}

Measured memory_bytes: 3200
local mfl = math.floor

local n, k, c = io.read("*n", "*n", "*n", "*l")
local s = io.read()
local t = {}
for i = 1, n do
  if s:sub(i, i) == "o" then
    table.insert(t, i)
  end
end
local inf = 1000000007
local pre = {}
do
  local pos = 0
  local cur = -inf
  for i = 1, #t do
    if cur + c < t[i] then
      pos = pos + 1
      cur = t[i]
      pre[pos] = i
    end
  end
end
if k < #pre then
  print("")
  os.exit()
end

local suf = {}
for i = 1, k do suf[i] = -1 end
do
  local pos = k + 1
  local cur = inf
  for i = #t, 1, -1 do
    if t[i] < cur - c then
      pos = pos - 1
      cur = t[i]
      suf[pos] = i
    end
  end
end

-- print(table.concat(t, " "))
-- print(table.concat(pre, " "))
-- print(table.concat(suf, " "))

if #t == 1 then
  print(t[1])
  os.exit()
end
for i = 1, k do
  if pre[i] == suf[i] then
    print(t[pre[i]])
  end
end


Measured memory_bytes: 24884
#include<iostream>
#include<iomanip>
#include<math.h>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<complex>

#define INF (long long)1000000000
#define MOD 1000000007
#define EPS 1e-8

#define REP(i, m) for(long long i = 0; i < m; ++i)
#define FOR(i, n, m) for(long long i = n; i < m; ++i)
#define ALL(v) v.begin(), v.end()
#define pb push_back

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
typedef long double ld;

int main() {
	int n;
	cin>>n;
	vector<int> a(n);
	REP(i,n)cin>>a[i];
	int c = 0;
	REP(i,n) {
		if(a[a[i]-1]-1==i)++c;
	}
	cout<<c/2<<endl;
}


Measured memory_bytes: 640
#include <bits/stdc++.h>
// iostream is too mainstream
#include <cstdio>
// bitch please
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <list>
#include <cmath>
#include <iomanip>
#include <time.h>
#define dibs reserve
#define OVER9000 1234567890
#define ALL_THE(CAKE,LIE) for(auto LIE =CAKE.begin(); LIE != CAKE.end(); LIE++)
#define tisic 47
#define soclose 1e-8
#define chocolate win
// so much chocolate
#define patkan 9
#define ff first
#define ss second
#define abs(x) (((x) < 0)?-(x):(x))
#define uint unsigned int
#define dbl long double
#define pi 3.14159265358979323846
using namespace std;
// mylittledoge

using cat = long long;

#ifdef DONLINE_JUDGE
	// palindromic tree is better than splay tree!
	#define lld I64d
#endif

int main() {
	cin.sync_with_stdio(0);
	cin.tie(0);
	cout << fixed << setprecision(10);
	int N, MX = 200000;
	cin >> N;
	vector<int> C(N);
	vector< vector<int> > pos(MX+1);
	vector<int> ppos(MX+1, 0);
	for(int i = 0; i < N; i++) {
		cin >> C[i];
		pos[C[i]].push_back(i);
		ppos[C[i]]++;
	}
	vector<cat> ans(N+1, 0);
	cat mod = 1000000007;
	ans[N] = 1;
	vector<cat> sums(MX+1, 0);
	for(int i = N-1; i >= 0; i--) {
		ppos[C[i]]--;
		if(ppos[C[i]]+1 == (int)pos[C[i]].size()) {
			sums[C[i]] += ans[i+1];
			if(sums[C[i]] >= mod) sums[C[i]] -= mod;
		}
		else if(i < N-1 && C[i+1] != C[i]) {
			sums[C[i]] += ans[i+1];
			if(sums[C[i]] >= mod) sums[C[i]] -= mod;
		}
		ans[i] = sums[C[i]];
	}
	cout << ans[0] << "\n";
	return 0;
}

// look at my code
// my code is amazing


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

using namespace std;

typedef long long ll;

int main() {
  int N;
  cin >> N;
  vector<int> a(N);
  for (int i = 0; i < N; ++i) {
    cin >> a[i];
  }
  vector<int> b(N, 0);
  for (int i = N - 1; i >= 0; --i) {
    int sum = 0;
    for (int j = 2; j < 2e6; ++j) {
      if ((i + 1) * j - 1 < N) sum += b[(i + 1) * j - 1];
      else break;
    }
    b[i] = (sum + a[i]) % 2;
  }
  int M = 0;
  for (int i = 0; i < N; ++i) {
    if (b[i] > 0) M++;
  }
  cout << M << endl;
  int cnt = 0;
  for (int i = 0; i < N; ++i) {
    if (b[i] > 0) {
      cnt++;
      cout << i + 1 << (cnt == M ? "\n" : " ");
    }
  }
}

Measured memory_bytes: 2432
#include "bits/stdc++.h"
using namespace std;
int main() {
	int n;
	while (cin>>n,n) {
		string s;
		bool up = 0;
		bool l = 0, r = 0;
		int ans = 0;
		for (int i = 0; i < n; i++) {
			cin >> s;
			if (s == "lu") {
				if (r) {
					if (!up) ans++;
					up = 1;
				}
				l = 1;
			}
			else if (s == "ru") {
				if (l) {
					if (!up) ans++;
					up = 1;
				}
				r = 1;
			}
			else if (s == "ld") {
				if (!r) {
					if (up) ans++;
					up = 0;
				}
				l = 0;
			}
			else {
				if (!l) {
					if (up) ans++;
					up = 0;
				}
				r = 0;
			}
		}
		cout << ans << endl;
	}
}

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

signed main(){
	int H,W; cin>>H>>W;
	vector<string> field(H);
	for(int i=0;i<H;i++)cin>>field[i];
	vector<vector<int>> dis_tate(W,vector<int>(0));
	vector<vector<int>> dis_yoko(H,vector<int>(0));
	vector<vector<int>> tate(W,vector<int>(H,0));
	vector<vector<int>> yoko(H,vector<int>(W,0));
	for(int i=0;i<H;i++){
		for(int j=0;j<W;j++){
			if(field[i][j]=='#'){
				dis_tate[j].push_back(i);
				dis_yoko[i].push_back(j);
			}
		}
	}
	for(int i=0;i<H;i++){
		if(dis_yoko[i].size()==0){
			for(int k=0;k<W;k++)yoko[i][k]=W-1;
		}
		else {
			int t1=-1,t2;//ここもしかしたらt1=0かもしれない、よくわからない
			for(int j=0;j<dis_yoko[i].size();j++){
				t2=dis_yoko[i][j];
				for(int k=t1+1;k<t2;k++)yoko[i][k]=t2-t1-2;
				t1=t2;
			}
			for(int k=dis_yoko[i][dis_yoko[i].size()-1]+1;k<W;k++){
				yoko[i][k]=W-dis_yoko[i][dis_yoko[i].size()-1]-2;
				//ここの添字もあやしい
			}
		}
	}
	for(int i=0;i<W;i++){
		if(dis_tate[i].size()==0){
			for(int k=0;k<H;k++)tate[i][k]=H-1;
		}
		else {
			int t1=-1,t2;//ここもしかしたらt1=0かもしれない、よくわからない
			for(int j=0;j<dis_tate[i].size();j++){
				t2=dis_tate[i][j];
				for(int k=t1+1;k<t2;k++)tate[i][k]=t2-t1-2;
				t1=t2;
			}
			for(int k=dis_tate[i][dis_tate[i].size()-1]+1;k<H;k++){
				tate[i][k]=H-dis_tate[i][dis_tate[i].size()-1]-2;
				//ここの添字もあやしい
			}
		}
	}
	int ans=0;
	//cout<<"tate"<<endl;
	for(int i=0;i<H;i++){
		for(int j=0;j<W;j++){
	//		cout<<tate[j][i];
			int tmp=tate[j][i]+yoko[i][j];
			ans=max(ans,tmp);
		}
	//	cout<<endl;
	}
	
	cout<<ans+1<<endl;
}

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

using namespace std;

static const int INF = 1e9 + 7;

void hawawa()
{
  long long k, a, b;
  cin >> k >> a >> b;
  long long ans = 1;
  k -= a;
  if (k <= 0) {
    cout << ans << "\n";
    return;
  }
  if (a > b) {
    a -= b;
    ans += (k / a + !!(k % a)) * 2;
    cout << ans << "\n";
  } else {
    cout << "-1\n";
  }
}
int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  hawawa();
}

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

using namespace std;

const int maxn = 2e5 + 5,mod = 10399;

int n,p1,p2,p,a[maxn],b[maxn],l,p3,p4;

long long ans;

int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>a[i];
    for(int i=0;i<n;i++)
    {
        l = i / 2;
        b[l] = a[n - (l*2) - 1];
        if(n - (l*2) - 2 < 0)
            break;
        b[n - l - 1] = a[n - (l*2) - 2];
        l++;
    }
    for(int i=0;i<n;i++)
        cout<<b[i]<<" ";
}


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

using namespace std;
using ll = long long;

#define int ll
#define all(x) x.begin(), x.end()
#define mp make_pair
#define mt make_tuple
#define x first
#define y second
#define pb push_back
#define sz(x) int(x.size())



signed main() {
#ifdef LC
	assert(freopen("input.txt", "r", stdin));
#endif
	ios::sync_with_stdio(0);
	cin.tie(0);
	int n;
	cin >> n;
	string a;
	string b;
	cin >> a >> b;
	for (int i = 0; i < n; ++i) {
		cout << a[i] << b[i];
	}
	cout << endl;
	return 0;
}


Measured memory_bytes: 256