akhauriyash/Code-Regression huggingface dataset:
while 1:
    h, w = map(int, input().split())
    if h == 0:
        break
    d = {}
    for i in range(h):
        s = input()
        for j in range(w):
            if s[j] != '_':
                d[s[j]] = [j, i]
    s = input()
    cnt = 0
    for i in range(len(s)):
        if i == 0:
            cnt += d[s[i]][0] + d[s[i]][1] + 1
        else:
            cnt += abs(d[s[i]][0]-d[s[i-1]][0]) + abs(d[s[i]][1]-d[s[i-1]][1]) + 1
    print(cnt)


Measured memory_bytes: 5624
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[100005];
bool k=true;
int t;
int main(void){
	int n; cin>>n;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	if(n%3==0){
		for(int i=0;i<n;i++){
			t=t^a[i];
		}
		if(t!=0){
			k=false;
		}
	}else{
		for(int i=0;i<n;i++){
			if(a[i]!=0){
				k=false;
			}
		}
	}
	if(k){
		cout<<"Yes"<<endl;
	}else{
		cout<<"No"<<endl;
	}
	
}


Measured memory_bytes: 640
n = int(input())


# 入力 : 自然数     ex) 12
# 出力 : 約数リスト ex) [(2,2),(3,1)]
def factorize(n):
    fct = []  # prime factor
    b, e = 2, 0  # base, exponent
    while b * b <= n:
        while n % b == 0:
            n = n // b
            e = e + 1
        if e > 0:
            fct.append((b, e))
        b, e = b + 1, 0
    if n > 1:
        fct.append((n, 1))
    return fct


divList = [0 for i in range(n + 1)]
# divList[1] = 1
for i in range(2, n + 1):
    tmp = factorize(i)
    for j in range(len(tmp)):
        divList[tmp[j][0]] += tmp[j][1]
# print(divList)
# print(sum())
count = 0

# a^d * b^e * c^fの約数は(d+1)*(e+1)*(f+1)個
# つまり75個約数があるとは
# 3*5*5=(2+1)*(4+1)*(4+1)
# 3*25=(2+1)*(24+1)
# 5*15=(4+1)*(14+1)
# 75=(74+1)
# よって各約数を数えればいいだけ
for i in range(len(divList) - 2):
    for j in range(i + 1, len(divList) - 1):
        for k in range(j + 1, len(divList)):
            if divList[i] >= 2 and divList[j] >= 4 and divList[k] >= 4:
                # print("i:{} j:{} k:{} sum:{}".format(i, j, k, (i ** 2) * (j ** 4) * (k ** 4)))
                count += 1
            if divList[i] >= 4 and divList[j] >= 2 and divList[k] >= 4:
                # print("i:{} j:{} k:{} sum:{}".format(i, j, k, (i ** 4) * (j ** 2) * (k ** 4)))
                count += 1
            if divList[i] >= 4 and divList[j] >= 4 and divList[k] >= 2:
                # print("i:{} j:{} k:{} sum:{}".format(i, j, k, (i ** 4) * (j ** 4) * (k ** 2)))
                count += 1
for i in range(len(divList) - 1):
    for j in range(i + 1, len(divList)):
        if (divList[i] >= 2 and divList[j] >= 24):
            # print("i:{} j:{} sum:{}".format(i, j, (i ** 2) * (j ** 24)))
            count += 1
        if (divList[i] >= 24 and divList[j] >= 2):
            # print("i:{} j:{} sum:{}".format(i, j, (i ** 24) * (j ** 2)))
            count += 1
        if (divList[i] >= 14 and divList[j] >= 4):
            # print("i:{} j:{} sum:{}".format(i, j, (i ** 14) * (j ** 4)))
            count += 1
        if divList[i] >= 4 and divList[j] >= 14:
            # print("i:{} j:{} sum:{}".format(i, j, (i ** 4) * (j ** 14)))
            count += 1
for i in range(len(divList)):
    if divList[i] >= 74:
        # print("i:{} sum:{}".format(i, (i ** 74)))
        count += 1
print(count)

Measured memory_bytes: 3188
#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define all(x) (x).begin(), (x).end()
using ll = long long;
using namespace std;
template <typename T>
using vec = std::vector<T>;

int main() {
    string S;
    cin >> S;
    int N = S.size();
    map<int,int> mp;
    ll ans = 0;
    int keta = 1;
    int now = 0;
    reverse(all(S));
    mp[0] = 1;
    for(auto e:S){
        int s = e - '0';
        now = (now + s*keta)%2019;
        ans += mp[now];
        ++mp[now];
        keta = (keta*10)%2019;
    }
    cout << ans << endl;
}

Measured memory_bytes: 3704
import java.util.HashSet;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

		HashSet<Integer> lista = new HashSet<Integer>();
		for(int i =0; i < 3; i++) {
			lista.add(scan.nextInt());
		}
        System.out.println(lista.size());
	}
}

Measured memory_bytes: 21844
#include "bits/stdc++.h"
using namespace std;

int main() {
	int X, Y, S;
	while (cin >> X >> Y >> S) {
		if (X == 0 && Y == 0 && S == 0) return 0;
		int MAX = 0;
		for (int i = 1; i < S; i++) {
			for (int j = i; j < S; j++) {
				int k = i * (100 + X) / 100 + j * (100 + X) / 100;
				if (k == S) {
					MAX = max(MAX, i * (100 + Y) / 100 + j * (100 + Y) / 100);
				}
				if (k > S) break;
			}
		}
		cout << MAX << endl;
	}
}


Measured memory_bytes: 3072
// I SELL YOU...! 
#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>
#include<queue>
#include<chrono>
#include<iomanip>
#include<map>
#include<set>
using namespace std;
using ll = long long;
using P = pair<ll,ll>;
void init_io(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << setprecision(10);
}
ll dp[1100000][2];
signed main(){
  init_io();
  string s;
  vector<ll> n;
  fill(dp[0],dp[1100000],1000000000000);
  ll m;
  cin >> s;
  m = s.size();
  reverse(s.begin(),s.end());
  for(char c:s){
    n.push_back(c-'0');
  }
  dp[0][0] = 0;
  for(int i=0;i<m;i++){
    for(int j=0;j<2;j++){
      dp[i+1][0] = min(dp[i+1][0],dp[i][j]+j+n[i]);
      dp[i+1][1] = min(dp[i+1][1],dp[i][j]+10-j-n[i]);
    }
  }
  cout << min(dp[m][0],dp[m][1]+1)<<endl;
}


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

void resoltion(int A, int B, int C, int D)
{
	if (B < C) {
		cout << 0;
		return;
	}

	if (B < D) 
	{
		cout << B - C;
		return;
	}
	else
	{
		cout << D - C;
		return;
	}
}

int main()
{
	int A, B, C, D;
	cin >> A >> B >> C >> D;

	if (A < C)
		resoltion(A, B, C, D);
	else
		resoltion(C, D, A, B);

	return 0;
}

Measured memory_bytes: 256
import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        long[][] c = new long[n+1][n+1];
        for(int i = 0; i<n+1; i++) {
            c[i][0] = 1;
        }
        for(int i = 1; i<n+1; i++) {
            for(int j = 1; j<n+1; j++) {
                c[i][j] = (c[i - 1][j] + c[i - 1][j - 1]) % (1000000007);
            }
        }
        for(int i = 1; i<=k; i++) {
            long ans = (c[n-k+1][i]*c[k-1][i-1])%(1000000007);
            System.out.println(ans);
        }

    }
}

Measured memory_bytes: 83156
import sys
from operator import itemgetter
import heapq

def solve():
    input = sys.stdin.readline
    N = int(input())
    town = dict()
    road = [None] * N
    roadx, roady = [None] * N, [None] * N
    for i in range(N):
        x, y = map(int, input().split())
        town[(x, y, i)] = i
        road[i] = (x, y, i)
        roadx[i] = (x, y, i)
        roady[i] = (x, y, i)
    roadx.sort()
    roadx_id = dict()
    roady.sort(key = itemgetter(1))
    roady_id = dict()
    for i in range(N):
        roadx_id[roadx[i]] = i
        roady_id[roady[i]] = i

    visited = [False] * N
    q = []
    heapq.heapify(q)
    heapq.heappush(q, (0, 0)) #(cost, town_id)
    cost = 0
    while q:
        add_cost, id = heapq.heappop(q)
        #print(add_cost, id, cost)
        #print(visited)
        if not visited[id]:
            cost += add_cost
            visited[id] = True
            for s in range(2):
                nx = roadx_id[road[id]] + (-1) ** s #roadxにおけるid
                if 0 <= nx < N:
                    if not visited[town[roadx[nx]]]: heapq.heappush(q, (min(abs(road[id][0] - roadx[nx][0]), abs(road[id][1] - roadx[nx][1])), town[roadx[nx]]))
                
                ny = roady_id[road[id]] + (-1) ** s #roadyにおけるid
                if 0 <= ny < N:
                    if not visited[town[roady[ny]]]: heapq.heappush(q, (min(abs(road[id][1] - roady[ny][1]), abs(road[id][1] - roady[ny][1])), town[roady[ny]]))
    
    print(cost)

    return 0

if __name__ == "__main__":
    solve()

Measured memory_bytes: 78424
#include <iostream>

using namespace std;

int main()
{
    int w, h, x, y, r;
    cin >> w >> h >> x >> y >> r;
    if(x-r>=0 && y-r>=0 && x+r<=w && y+r<=h)
        cout << "Yes" << endl;
    else 
        cout << "No" << endl;
}


Measured memory_bytes: 3104
#include <iostream>
#include <map>
#include <queue>
using namespace std;
typedef pair<int,int> P;
int N,M,K;
int D[110];
int ok[110] = {};
int V[110][110];
int dist[1<<16] = {};


int bfs(map<int,int> &m){
    dist[(1<<M)-1] = 0;
    queue<int> Q;
    Q.push((1<<M)-1);
    while(!Q.empty()){
        int S = Q.front(); Q.pop();
        for(int i=0;i<K;i++){
            int T = 0;
            for(int j=0;j<M;j++){
                if(!(S&(1<<j))) continue;
                int ne = V[D[j]][i];
                if(m.count(ne)) T |= (1<<m[ne]);
            }
            if(dist[T]==-1){
                dist[T] = dist[S]+1;
                Q.push(T);
            }
        }
    }
    return dist[0];
}

int main(){
    cin >> N >> M >> K;
    map<int,int> m;
    for(int i=0;i<M;i++){
        cin >> D[i];
        D[i]--;
        m[D[i]] = i;
    }
    for(int i=0;i<N;i++) for(int j=0;j<K;j++){cin >> V[i][j]; V[i][j]--;}
    for(int S=0;S<(1<<M);S++) dist[S] = -1;
    cout << bfs(m) << endl;
}


Measured memory_bytes: 3588
using System;
using System.Linq;
using System.Collections.Generic;

class Cmondai
{
    static void Main()
    {
        var line = Console.ReadLine().Split(' ').Select(x => decimal.Parse(x)).ToArray();
        var A = line[0];
        var B = line[1];
        var C = line[2];
        var D = line[3];
        var E = line[4];
        var F = line[5];

        decimal max = -1;
        decimal maxSugarWater = 0;
        decimal maxSugar = 0;

        var waterAmax = F / (A * 100);
        for (int i = 0; i <= waterAmax; ++i)
        {
            var bCount = (F - (A * i * 100)) / (B * 100);
            for (int j = 0; j <= bCount; ++j)
            {
                if (i == 0 && j == 0) continue;
                if (F < (A * i + B * j) * 100) break;
                var cCount = (F - (A * i * 100 + B * j * 100)) / C;
                for (int k = 0; k <= cCount; ++k)
                {
                    if (F < (A * i + B * j) * 100 + C * k) break;
                    var dCount = (F - ((A * i * 100 + B * j * 100) + C * k)) / D;
                    for (int l = 0; l <= dCount; ++l)
                    {
                        if (F < (A * i + B * j) * 100 + C * k + D * l) break;
                        if ((C * k + D * l) <= (i * A + j * B) * E)
                        {
                            var sugarWater = (A * i) * 100 + (B * j) * 100 + C * k + D * l;
                            var sugar = C * k + D * l;
                            var concentration = sugar == 0 ? 0 : sugar / sugarWater * 100;
                            if (max < concentration)
                            {
                                max = concentration;
                                maxSugarWater = sugarWater;
                                maxSugar = sugar;
                            }
                        }
                    }

                }
            }
        }
        Console.WriteLine($"{maxSugarWater} {maxSugar}");
    }
}

Measured memory_bytes: 13396
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
#include <stack>
#include <functional>
#include <set>
#include <map>
#include <deque>

#define GET_ARRAY_SIZE(a)   (sizeof(a)/sizeof(a[0]))

using namespace std;

struct Card{char suit; int value;};

void print_func(Card *array, int size){
    for (int j = 0; j < size; ++j) {
        cout << ( j ? " " : "" ) << array[j].suit << array[j].value;
    }
    cout << endl;
}

void bubble_sort(Card *array, int size){
    Card tmp;
    bool flag = true;
    while(flag) {
        flag = false;
        for (int i = size - 1; i > 0; --i) {
            if (array[i].value < array[i - 1].value) {
                tmp = array[i - 1];
                array[i - 1] = array[i];
                array[i] = tmp;
                flag = true;
            }
        }
    }
}

void selection_sort(Card* array, int size){
    int minj;
    Card tmp;
    bool flag;
    for (int i = 0; i < size; ++i) {
        minj = i;
        flag = false;
        for (int j = i; j < size; ++j) {
            if (array[j].value < array[minj].value) {
                minj = j;
                flag = true;
            }
        }

        if (flag) {
            tmp = array[i];
            array[i] = array[minj];
            array[minj] = tmp;
        }
    }
}

bool is_stable(Card *a1, Card *a2, int size){
    bool check = true;
    for (int i = 0; i < size; ++i) {
        if (a1[i].suit != a2[i].suit){
            check = false;
            break;
        }
    }
    return check;
}

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

    Card C1[N], C2[N];

    for (int i = 0; i < N; ++i) {
        cin >> C1[i].suit >> C1[i].value;
        C2[i] = C1[i];
    }

    bubble_sort(C1, GET_ARRAY_SIZE(C1));
    print_func(C1, GET_ARRAY_SIZE(C1));
    cout << "Stable" << endl;

    selection_sort(C2, GET_ARRAY_SIZE(C2));
    print_func(C2, GET_ARRAY_SIZE(C2));


    if(is_stable(C1, C2, N)){
        cout << "Stable" << endl;
    }else{
        cout << "Not stable" << endl;
    }

}

Measured memory_bytes: 3096
using System;
class Program{
    static void Main(string[]args){
        string[]t=Console.ReadLine().Split(' ');
        int N=int.Parse(t[0]);
        int K=int.Parse(t[1]);
        
        string[]a=Console.ReadLine().Split(' ');
        int[]A=new int[a.Length];
        for(int i=0;i<a.Length;i++){
            A[i]=int.Parse(a[i]);
        }
        if(N==K){
            Console.WriteLine(1);
        }
        else if((N-1)%(K-1)==0){
            Console.WriteLine((N-1)/(K-1));
        }else if((N-1)%(K-1)!=0){
            Console.WriteLine((N-1)/(K-1)+1);
        }    
        
    }
}

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

using namespace std;
int main(int argc, const char * argv[]) {
    int q, i, m, n, sl1, sl2;
    cin >> q;
    vector<string> strlist;
    string str, str1, str2;
    for(i = 0;i < q;i++){
        cin >> str;
        strlist.push_back(str);
        cin >> str;
        strlist.push_back(str);
    }
    
    //start
    for(i = 0;i < q*2;i += 2){
        str1 = strlist[i];
        sl1 = str1.length();
        str2 = strlist[i+1];
        sl2 = str2.length();
        int dp[sl1+1][sl2+1];
        for(m = 0;m <= sl2;m++){
            dp[0][m] = 0;
        }
        for(m = 0;m <= sl1;m++){
            dp[m][0] = 0;
        }
        for(m = 1;m <= sl1;m++){
            for(n = 1;n <= sl2;n++){
                dp[m][n] = 0;
            }
        }
        for(m = 1;m <= sl1;m++){
            for(n = 1;n <= sl2;n++){
                if(str1[m-1] == str2[n-1]){
                    dp[m][n] = dp[m-1][n-1] + 1;
                }else{
                    dp[m][n] = max(dp[m-1][n], dp[m][n-1]);
                }
            }
        }
        m = sl1;
        n = sl2;
        printf("%d\n", dp[m][n]);
        
    }
    return 0;
}


Measured memory_bytes: 7228
#include<iostream>
using namespace std;
long long sum=0,num[150];
int main(){
    ios::sync_with_stdio(false);
    int n=0;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>num[i],sum+=num[i];
    int t=0;
    cin>>t;
    for(int i=1;i<=t;i++){
        long long a=0,b=0;
        cin>>a>>b;
        cout<<sum-num[a]+b<<endl;
    }
    return 0;
}

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

void solve(long long x, long long a, long long b)
{
    if (abs(x - a) < abs(x - b))
    {
        cout << "A" << endl;
    }else{
        cout << "B" << endl;
    }
}

int main()
{
    long long x;
    scanf("%lld", &x);
    long long a;
    scanf("%lld", &a);
    long long b;
    scanf("%lld", &b);
    solve(x, a, b);
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#include <math.h>
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 int64_t INF = 1LL << 60;

int main() {
 int N;
 cin>>N;
 int64_t ans=0;
 for(int i=1;i<N;i++){
  ans+=i;
 }
 cout<<ans<<endl;
 return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
 
int main(){
    int h,w;
    cin>>h>>w;
    string s[h];
    int cnt=0;
    vector<pair<int,int>> p;
    for(int i=0;i<h;i++){
        cin>>s[i];
        for(int j=0;j<w;j++){
            if(s[i][j]=='#'){
                cnt++;
                p.push_back(make_pair(i,j));
            }
        }
    }
    int y[4]={0,1,0,-1};
    int x[4]={1,0,-1,0};
    int ans=0;
    while(cnt!=h*w){
        ans++;
        vector<pair<int,int>> v;
        for(auto i:p){
            for(int j=0;j<4;j++){
                if(i.first+x[j]>=0 && i.first+x[j]<h && i.second+y[j]<w && i.second+y[j]>=0){
                    if(s[i.first+x[j]][i.second+y[j]]=='.'){
                        v.push_back(make_pair(i.first+x[j],i.second+y[j]));
                        s[i.first+x[j]][i.second+y[j]]='#';
                        cnt++;
                    }
                }
            }
        }
        p=v;
    }
    cout<<ans<<endl;
 
}

Measured memory_bytes: 14212
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _0003
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] iArray = new int[3];
            int cnt = int.Parse(Console.ReadLine());
            

            for (int i = 0; i < cnt; i++)
            {
                var str = Console.ReadLine();
                var sArray = str.Split();

                for (int j = 0; j < sArray.Length; j++)
                {
                    iArray[j] = int.Parse(sArray[j]);
                }
                Array.Sort(iArray);

                if (iArray[0] * iArray[0] + iArray[1] * iArray[1] == iArray[2] * iArray[2])
                {
                    Console.WriteLine("YES");
                }
                else
                {
                    Console.WriteLine("NO");
                }
                    
            }
        }
    }
}

Measured memory_bytes: 5600
#include <bits/stdc++.h>
using namespace std;
#define rep(i, c) for(long long i=0; i<(long long)c; i++)
int main() {
	int n1,n2,n3,n4,n5;

	cin>>n1>>n2>>n3>>n4>>n5;
	if (n1==0) cout <<1<<endl;
	if (n2==0) cout <<2<<endl;
	if (n3==0) cout <<3<<endl;
	if (n4==0) cout <<4<<endl;
	if (n5==0) cout <<5<<endl;

	return 0;
}


Measured memory_bytes: 3632
#include<stdio.h>
int main(){
int a,b,n,ans=0,i;
while(scanf("%d %d %d\n",&a,&b,&n)!=EOF){
for(i=0;i<n;i++){
a=a*10;
ans=ans+(a/b%10);
a=a%b;
if(a==0){
break;
}
}
printf("%d\n",ans);
ans=0;
}
return 0;
}


Measured memory_bytes: 2064
class RMaxQ:
    
    __slots__ = ["n", "data", "id"]
    
    def __init__(self, li):
        self.n = len(li)
        self.id = -float("inf")
        self.data = [self.id]*self.n + li
        for i in range(self.n - 1, 0, -1):
            self.data[i] = max(self.data[2*i], self.data[2*i+1])
    
    def get(self, i):
        return self.data[i+self.n]
    
    def update(self, i, a):
        i += self.n
        self.data[i] = a
        while i > 1:
            i //= 2
            self.data[i] = max(self.data[2*i], self.data[2*i+1])
    
    def add(self, i, a):
        i += self.n
        self.data[i] += a
        while i > 1:
            i //= 2
            self.data[i] = max(self.data[2*i], self.data[2*i+1])
    
    def fold(self, l, r):
        l += self.n
        r += self.n
        res = self.id
        while l < r:
            if l % 2:
                res = max(self.data[l], res)
                l += 1
            if r % 2:
                r -= 1
                res = max(res, self.data[r])
            l //= 2
            r //= 2
        return res
    
    def max_right(self, l, r, check):
        l += self.n
        r += self.n
        left_li = []
        right_li = []
        while l < r:
            if l % 2:
                left_li.append(l)
                l += 1
            if r % 2:
                r -= 1
                right_li.append(r)
            l //= 2
            r //= 2
        temp = self.id
        for idx in (left_li + right_li[::-1]):
            if not check(max(temp, self.data[idx])):
                temp = max(temp, self.data[idx])
            else:
                break
        else:
            return -1
        while idx < self.n:
            if check(max(temp, self.data[2*idx])):
                idx = 2*idx
            else:
                temp = max(temp, self.data[2*idx])
                idx = 2*idx+1
        return idx - self.n
    
    def min_left(self, l, r, check):
        l += self.n
        r += self.n
        left_li = []
        right_li = []
        while l < r:
            if l % 2:
                left_li.append(l)
                l += 1
            if r % 2:
                r -= 1
                right_li.append(r)
            l //= 2
            r //= 2
        temp = self.id
        for idx in (right_li + left_li[::-1]):
            if not check(max(self.data[idx], temp)):
                temp = max(self.data[idx], temp)
            else:
                break
        else:
            return -1
        while idx < self.n:
            if check(max(self.data[2*idx+1], temp)):
                idx = 2*idx+1
            else:
                temp = max(temp, self.data[2*idx+1], temp)
                idx = 2*idx
        return idx - self.n

import sys
input = sys.stdin.readline
n, q = map(int, input().split())
A = list(map(int, input().split()))
seg = RMaxQ(A)
for _ in range(q):
    t, x, v = map(int, input().split())
    x -= 1
    if t == 1:
        seg.update(x, v)
    elif t == 2:
        print(seg.fold(x, v))
    else:
        ans = seg.max_right(x, n, lambda x: x>=v)
        if ans == -1:
            print(n+1)
        else:
            print(ans+1)


Measured memory_bytes: 96300
#include<iostream>
#include<sstream>

using namespace std;

int main() {
	int x;
	cin >> x;
	//YYY point
	//500 1000
	//5 5
	//100 50 10 1 =0

	int a,y;
	a = x / 500;
	y = x % 500;
	int b, z;
	b = y / 5;
	z = y % 5;

	int po;
	po = a * 1000 + b *5;
	cout << po << endl;
	
	return 0;

}

Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

void chmax(long long *a, long long b){
  if( *a < b ) *a = b;
}

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

vector<vector<long long> > abc(n, vector<long long>(3));
for(int i=0; i<n; i++){
  for(int j=0; j<3; j++) cin >> abc[i][j];
}

// 1 = a, 2 = b, 3 = c
vector<vector<long long> > dp(n, vector<long long>(3, 0));
dp[0][0] = abc[0][0];
dp[0][1] = abc[0][1];
dp[0][2] = abc[0][2];

for(int i=1; i<n; i++){
    chmax(&dp[i][2], dp[i-1][0] + abc[i][2]);
    chmax(&dp[i][1], dp[i-1][0] + abc[i][1]);
    chmax(&dp[i][2], dp[i-1][1] + abc[i][2]);
    chmax(&dp[i][0], dp[i-1][1] + abc[i][0]);
    chmax(&dp[i][1], dp[i-1][2] + abc[i][1]);
    chmax(&dp[i][0], dp[i-1][2] + abc[i][0]);
}

long long max = 0;
chmax(&max, dp[n-1][0]);
chmax(&max, dp[n-1][1]);
chmax(&max, dp[n-1][2]);
cout << max << endl;


  return 0;
}


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

#define M 1046257
#define NIL (-1)
#define L 14

char H[M][L];

int getChar(char ch) {
  if ( ch == 'A' ) return 1;
  else if ( ch == 'C' ) return 2;
  else if ( ch == 'G' ) return 3;
  else if ( ch == 'T' ) return 4;
  return 0;
}

long long getKey(char str[]) {
  long long sum = 0, p = 1, i;
  for(i=0;i<strlen(str);i++) {
    sum += p*(getChar(str[i]));
    p*= 5;
  }
  return sum;
}

int h1(int key){ return key % M; }
int h2(int key){ return 1 + (key % (M-1)); }

int find(char str[]) {
  long long key, i, h;
  key = getKey(str); 
  for(i=0; ;i++) {
    h = (h1(key) + i*h2(key)) % M;
    if( strcmp(H[h],str) == 0) return 1;
    else if ( strlen(H[h]) == 0 ) return 0;
  }
  return 0;
}

int insert(char str[]) {
  long long key, i, h;
  key = getKey(str);
  for(i=0; ; i++) {
    h = (h1(key) + i * h2(key)) %M;
    if(strcmp(H[h],str) == 0) return 1;
    else if(strlen(H[h]) == 0) {
      strcpy(H[h],str);
      return 0;
    }
  }
  return 0;
}

int main(void) {
  int i, n;
  char str[L], com[9];
  for(i=0;i<M;i++) H[i][0] = '\0';
  scanf("%d",&n);
  for(i=0;i<n;i++) {
    scanf("%s %s",com,str);
    if(com[0] == 'i') {
      insert(str);
    } else {
      if(find(str)){
        printf("yes\n");
      } else {
        printf("no\n");
      }
    }
  }
  return 0;
}



Measured memory_bytes: 16056
//Totka hai dosto
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int ll

int32_t main()
{
	int k;
	cin>>k;
	string s;
	cin>>s;
	string add="...";
	int n=s.length();
	if(n<=k)
	{cout<<s<<"\n";}
	else
	{
		for(int i=0;i<k;i++)
		cout<<s[i];
		cout<<add;
	}
}

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

typedef struct {
	char name[12];
	int disp_num;
	int disp_time[30];
	int points;
} kyara_t;

int kyara_num;
kyara_t kyara[20];

int all_disp_num[30];

int main(void) {
	int i,j;
	int min_id;
	while(1) {
		scanf("%d",&kyara_num);
		if(kyara_num==0)break;
		memset(kyara,0,sizeof(kyara));
		memset(all_disp_num,0,sizeof(all_disp_num));
		for(i=0;i<kyara_num;i++) {
			scanf("%s%d",kyara[i].name,&kyara[i].disp_num);
			for(j=0;j<kyara[i].disp_num;j++) {
				scanf("%d",&kyara[i].disp_time[j]);
			}
		}
		for(i=0;i<kyara_num;i++) {
			for(j=0;j<kyara[i].disp_num;j++) {
				kyara[i].points+=kyara_num;
				all_disp_num[kyara[i].disp_time[j]]++;
			}
		}
		for(i=0;i<kyara_num;i++) {
			for(j=0;j<kyara[i].disp_num;j++) {
				kyara[i].points-=all_disp_num[kyara[i].disp_time[j]]-1;
			}
		}
		for(i=1,min_id=0;i<kyara_num;i++) {
			if(kyara[i].points<kyara[min_id].points) {
				min_id=i;
			} else if(kyara[i].points==kyara[min_id].points) {
				if(strcmp(kyara[i].name,kyara[min_id].name)<0) {
					min_id=i;
				}
			}
		}
		printf("%d %s\n",kyara[min_id].points,kyara[min_id].name);
	}
	return 0;
}

Measured memory_bytes: 0
# coding: utf-8
# Your code here!
import sys
sys.setrecursionlimit(10**7)
MOD=10**9+7

class Bit:
    def __init__(self, n):
        self.size = n
#        self.node = [0] * (n + 1)
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        i+=1
        s = 0
        while i > 0:
            s = max(s,self.tree[i])
            i -= i & -i
        return s
 
    def add(self, i, x):
        i+=1
#        self.node[i] += x
        while i <= self.size:
            self.tree[i] = max(self.tree[i],x)
            i += i & -i

#    def get(self,i)
#        return self.node(i+1)

n=int(input())
H = [int(i) for i in input().split()]
A = [int(i) for i in input().split()]

modosu = sorted(list(set(H)))
zaatu = {h:j for j,h in enumerate(modosu)}

#print(modosu)
#print(zaatu)

dp = Bit(n)
for i in range(1,n+1):
#    print(i,zaatu[i])
    dp.add(zaatu[H[i-1]], dp.sum(zaatu[H[i-1]])+A[i-1])

print(dp.sum(n-1))








Measured memory_bytes: 60612
using System;
using System.Linq;
class Program
    {
        static void Main(string[] args)
        {
            int[] input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            Console.WriteLine(new Calu().calu(input));
        }

        public class Calu{
            public int calu(int[] input){
                if(Math.Abs(input[1]-input[2])<=input[0]){
                    return 0;
                }else{
                    return Math.Abs(input[1] - input[2]) - input[0];
                }        
            }
        }
    }

Measured memory_bytes: 13396
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <utility>
#include <iomanip>
#include <tuple>
#include <numeric>
#include <cstdio>
#include <cmath>
using namespace std;
using ll = long long;
const int INF = 1e9;

int main() {
    int a, b, c, d; cin >> a >> b >> c >> d;
    while (true) {
        if (c <= 0) {
            cout << "Yes\n";
            return 0;
        }
        if (a <= 0) {
            cout << "No\n";
            return 0;
        }
        c -= b;
        a -= d;
    }
}


Measured memory_bytes: 3100
#include <stdio.h>
#include <stdlib.h>

void DrawRect(int h, int w)
{
	int i,j;
	for (i = 0; i < h; i++)
	{
		for (j = 0; j < w; j++)
		{
			if (i != 0 && i != (h-1) && j > 0 && j < (w-1))
			{
				printf(".");
			} else
			{
			printf("#");
			}
		}
		printf("\n");
	}
	printf("\n");
}

int main(int argc, char *argv[])
{
	int H, W;
	while (1)
	{
		scanf("%d %d", &H, &W);
		if (H == 0 && W == 0)
		{
			break;
		}
		DrawRect(H, W);
	}
	return 0;
}

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

int main(){
  int N;
  cin >> N;
  vector<tuple<string,int,int>> data(N);
  
  for(int i=0;i<N;i++){
    string S;
    int P;
    cin >> S >> P;
    data.at(i) = make_tuple(S,-P,i+1);
  }
  
  sort(data.begin(),data.end());
  
  for(int i=0;i<N;i++){
    int ans;
    tie(ignore,ignore,ans)=data.at(i);
    cout << ans << endl;
  }
  
  return 0;
}


Measured memory_bytes: 256
#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 ALL(x) (x).begin(), (x).end()

using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const ll INF = 1e15;

int main() {
  ll x;
  cin >> x;
  ll ans = 0;
  ans += 1000 * (x / 500);
  x -= 500 * (x / 500);
  ans += 5 * (x / 5);
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 256
A1, A2, A3 = map(int,input().split())
print(min(abs(A1 - A2) + abs(A2 - A3), abs(A2 - A3) + abs(A3 - A1), abs(A1 - A3) + abs(A3 - A2), abs(A2 - A1) + abs(A1 - A3), abs(A3 - A2) + abs(A2 - A1), abs(A3 - A1) + abs(A1 - A2)))

Measured memory_bytes: 38256
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 1020
struct node
{
  int key;
  struct node *left, *right;
};
  
struct node T[MAX];

struct node *newNode(int item)
{
  struct node *temp =  (struct node *)malloc(sizeof(struct node));
  temp->key = item;
  temp->left = temp->right = NULL;
  return temp;
} 

void Preorder(struct node* root)
{
  

  if (root == NULL)
    return;
 

  printf(" ");
  printf("%d",root->key);
 
  Preorder(root->left); 
 
   
  Preorder(root->right);
} 

void inorder(struct node *root)
{
 

  if (root != NULL)
    {

      inorder(root->left);

      printf(" ");
      printf("%d", root->key);
     
      inorder(root->right);
    }
}
  

struct node* insert(struct node* node, int key)
{
    
  if (node == NULL) return newNode(key);
 
   
  if (key < node->key)
    node->left  = insert(node->left, key);
  else if (key > node->key)
    node->right = insert(node->right, key);   
 
   
  return node;
}
  
struct node* search(struct node* root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == NULL || root->key == key)
       return root;
    
    // Key is greater than root's key
    if (root->key < key)
       return search(root->right, key);
 
    // Key is smaller than root's key
    return search(root->left, key);
}


int main()
{
  int T[MAX];
  int z,n,i,j,a,hit;
  int count=0;
  char str[7];
  
  struct node *root = NULL;
  scanf("%d",&n);

  for(i=0;i<n;i++){
    scanf("%s",str);
    if(strcmp(str,"insert")==0){
      scanf("%d",&z);
      
      if(i==0)
	root = insert(root,z);
      else insert(root,z);}

    if(strcmp(str,"find")==0){
      scanf("%d",&a);
     
      if(search(root,a))
	
     printf("yes\n");
     
	else printf("no\n");
      }
 
    if(strcmp(str,"print")==0){
     
      inorder(root);
      printf("\n");
      Preorder(root);
      printf("\n");
    }}
  free(root);
  return 0;
}



Measured memory_bytes: 15200
# n = int(input())
a, b = map(int, input().split())
# s = input()

# // x + y = a
# // 2x + 4y = b
# 2y = b -2a
# y = (b-2a)//2
# x = a-y

# 2x = b-2a
ans1 = ((b - 2 * a) % 2) == 0
x2 = b - 2 * a
ans = True
if x2 % 2 != 0:
    ans = False
if x2 < 0:
    ans = False
x2 = x2 // 2
if a - x2 < 0:
    ans = False
if ans:
    print("Yes")
else:
    print("No")


Measured memory_bytes: 9184
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<cstring>
#include<climits>
#include<algorithm>
#include<vector>
#include<cmath>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<deque>
#include<tuple>
#include<list>
#include<unordered_map>
#include <random>
#define ll long long
#define pii pair<int,int>
#define pp pair<pair<ll, ll>,pair<ll, ll>>
#define pll pair<ll,ll>
#define vii vector<int>
#define vll vector<ll>
#define lb lower_bound
#define pb push_back
#define mp make_pair
#define fi first
#define sc second
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep2(i,a,b) for(ll i=a;i<b;i++)
#define repr(i,n) for(ll i=n-1;i>=0;i--)
#define all(x) x.begin(),x.end()
#define LB(v,x) (lower_bound(v.begin(),v.end(),x)-v.begin())
#define UB(v,x) (upper_bound(v.begin(),v.end(),x)-v.begin())
#define ERASE(v) v.erase(unique(v.begin(),v.end()),v.end())
// #define int ll
using namespace std;
const int INF = (1 << 30 ) - 1;
const ll LLINF = (1LL << 60LL);
const int MOD = 1000000007;
const int MAX = 510000;
const double pi = acos(-1);
const double eps = 1e-9;


int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(15);
    string s,t,ans;
    cin>>s>>t;
    ll n=s.size(),m=t.size();
    rep(i,n+m){
        ans[i]=' ';
    }
    rep(i,n){
        ans[i*2]=s[i];
    }
    rep(i,m){
        ans[i*2+1]=t[i];
    }
    rep(i,n+m){
        cout<<ans[i];
    }
    cout<<endl;
    return 0;
}


Measured memory_bytes: 256
object Main{
	def main(A:Array[String]){
		val s = new java.util.Scanner(System.in)
		val n = s.nextInt
		var m = s.nextLong
		val a = Array.fill(n)((s.nextLong,s.nextLong)).sortBy(o => o _1)
		var r = 0L
		for(o <- a) {
			val v = math.min(o._2,m)
			r += o._1 * v
			m -= v
		}
		println(r)
	}
}


Measured memory_bytes: 82072
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <iomanip>
#include <map>
#include <set>
#include <cmath>
#include <cstdio>
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define FOR(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define All(v) (v).begin(),(v).end()
typedef long long ll;

int main(){
    int a;
    cin >> a;
    cout << 3*a*a << endl;
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5+5 , M = 1e18+5, OO = 0x3f3f3f3f;
typedef long long ll;

int main()
{
    int n, k, h, c;
    c = 0;
    cin >> n >> k;
    for(int i=0; i<n; ++i)
    {
        cin >> h;
        if(h >= k) c++;
    }
    cout << c << endl;
	return 0;
}


Measured memory_bytes: 256
// 標準入力から一行を読み取り、指定の型に変換する
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()
}

// 標準入力から一行を読み取り、空白文字で分割し、各要素を指定の型に変換する関数
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

// ユークリッドの互除法
fn gcd(low: u64, high: u64) -> u64 {
    if low == 0 { high }
    else { gcd(high%low, low) }
}

fn main() {
    let abcd: Vec<u64> = read_vec();
    let a = abcd[0];
    let b = abcd[1];
    let c = abcd[2];
    let d = abcd[3];

    // B以下の整数で、CでもDでも割り切れない数の個数
    let bn = b - b/c as u64 - b/d as u64 + b / (c/gcd(c, d)*d) as u64;
    // A未満の整数で、CでもDでも割り切れない数の個数
    let an = (a-1) - (a-1)/c as u64 - (a-1)/d as u64 + (a-1) / (c/gcd(c, d)*d) as u64;

    println!("{}", bn - an);
}


Measured memory_bytes: 4352
#!/usr/bin/env python3
import sys


MOD = 1000000007  # type: int


def factor(n: int):
    i = 2
    cnt = 0
    while n % i == 0:
        n //= i
        cnt += 1
    if cnt > 0:
        yield i, cnt

    i = 3
    while i * i <= n:
        cnt = 0
        while n % i == 0:
            n //= i
            cnt += 1
        if cnt > 0:
            yield i, cnt
        i += 2

    if n > 1:
        yield n, 1


def comb(n: int, r: int):
    if n - r < r:
        return comb(n, n - r)
    ans = 1
    for i in range(r):
        ans *= n - i
    for i in range(r):
        ans //= i + 1
    return ans


def solve(N: int, M: int):
    ans = 1
    for _p, cnt in factor(M):
        ans *= comb(N - 1 + cnt, cnt) % MOD
        ans %= MOD
    print(ans)


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    M = int(next(tokens))  # type: int
    solve(N, M)


if __name__ == '__main__':
    main()


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

using namespace std;
inline void prep ()
{
  cin.tie (0);
  cin.sync_with_stdio (0);
};
const double pi = acos(-1.);
//printf("%.12lf\n",mid);
// __builtin_popcount(int) count 1's in binary
// get decimal pert of number
/*
double intpart;
double thiss = modf((double)(n*m)/(double)k, &intpart);
*/
// round = (int)(num+.5)
int mod = 1000000007;

long long mymod(long long num){
  if (num< 0 && !(abs(num)%mod == 0)){
    if (mod == 1){
      return 0;;
    }
    return mod-abs(num)%mod;
  }else{
    return num%mod;
  }
}
/*string sentence = "And I feel fine...";
    istringstream iss(sentence);
*/  
double eps = .000000001;

int main ()
{
  prep ();
  int n;
  cin >> n;
  int arr[n];
  long long fullxor = 0;
  for (int i=0; i<n; i++){
      cin >> arr[i];
      fullxor ^= arr[i];
  }
  for (int i=0; i<n; i++){
      long long num = fullxor^arr[i];
      if (arr[i] != num){
          cout << "No";
          return 0;
      }
  }
  cout << "Yes";
  return 0;
}


Measured memory_bytes: 640
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int main()
{
	int a[100005],n,i,mid;
	long long sum=0;
	cin>>n;
	for(i=0;i<n;++i)
		scanf("%d",&a[i]);
	if(n==2)
	{
		cout<<abs(a[0]-a[1]);
		return 0;
	}
	sort(a,a+n);
	mid=n/2;
	if(n%2)
	{
		if(a[mid]-a[mid-1]<a[mid+1]-a[mid])
		{
			for(i=0;i<mid-1;++i)
				sum-=2*a[i];
			sum-=a[mid]+a[mid-1];
			for(i=mid+1;i<n;++i)
				sum+=2*a[i];
		}
		else
		{
			for(i=0;i<=mid-1;++i)
				sum-=2*a[i];
			sum+=a[mid+1]+a[mid];
			for(i=mid+2;i<n;++i)
				sum+=2*a[i];
		}
		cout<<sum;
	}
	else
	{
		sum=a[mid]-a[mid-1];
		for(i=0;i<mid-1;++i)
			sum-=2*a[i];
		for(i=mid+1;i<n;++i)
			sum+=2*a[i];
		cout<<sum;
	}
	return 0;
}

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

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

    int r, d, x;
    cin >> r >> d >> x;

    for(int i = 0; i < 10; i++) {
    	x = r * x - d;
    	cout << x << endl;
    }
}

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

using namespace std;

int main(){
	ios_base::sync_with_stdio(false);
	int q;
	cin >> q;
	while(q--){
		string s, t;
		cin >> s >> t;
		const int n = s.size();
		if(s == t){
			cout << 0 << endl;
			continue;
		}
		int f = 0, b = n - 1, a = n - 1;
		while(s[f] == t[f]){ ++f; }
		while(s[b] == '0'){ --b; }
		while(t[a] == '0'){ --a; }
		int answer = 0;
		while(b > f){
			if(s[b - 1] == '1'){
				s[b] = '0';
			}else{
				s[b - 1] = '1';
				s[b] = '0';
			}
			--b;
			++answer;
		}
		while(b < a){
			if(s[b] == '0'){
				s[b] = '0';
				s[b + 1] = '1';
			}else{
				s[b + 1] = '1';
			}
			++b;
			++answer;
		}
		while(b > a){
			if(s[b - 1] == '0'){
				s[b] = '0';
				s[b - 1] = '1';
			}else{
				s[b] = '0';
			}
			--b;
			++answer;
		}
		cout << answer << "\n";
	}
	return 0;
}




Measured memory_bytes: 3216
import java.util.*;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		sc.close();
		int n = s.length();
		int ans[] = new int[n];
		int r = 0;
		int pre = 0;
		for (int i = 0; i < n; ++i) {
			if (s.charAt(i) == 'R')
				r = i;
			if (s.charAt(i) == 'L') {
				if (i == n - 1 || s.charAt(i + 1) == 'R') {
					ans[r] = (r - pre + 2) / 2 + (i - r) / 2;
					ans[r + 1] = (r - pre + 3) / 2 + (i - r - 1) / 2;
					pre = i + 1;
				}
			}
		}
		for (int a : ans)
			System.out.print(a + " ");
		System.out.println();
	}
}


Measured memory_bytes: 44240
#include<iostream>
#include<vector>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<sstream>
#include<cmath>
#include<numeric>
#include<map>
#include<stack>
#include<queue>
using namespace std;
int inf = 1000000000;

string dfs(string s){
  if( s.size() == 1 ){
    cout << s << endl;
    return "";
  }
  string t = "";
  for(int i=1; i<s.size(); i++){
    int a = s[i]-'0' + s[i-1]-'0';
    t += to_string(a%10);
  }
  dfs(t);
  return "";
}

int main(void) {

  string s;
  while(cin >> s){
    dfs(s);
  }

  return 0;
}

// EOF

Measured memory_bytes: 3212
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define ll              long long
#define pb              push_back
#define ppb             pop_back
#define endl            '\n'
#define mii             map<ll,ll>
#define pii             pair<ll,ll>
#define vi              vector<ll>
#define vs              vector<string>
#define all(a)          (a).begin(),(a).end()
#define F               first
#define S               second
#define sz(x)           ((ll)x.size())
#define hell            (1000000007)
#define inf             ((ll)5e18 + 5)
#define PI              ((double)3.14159265358979323844)
#define DECIMAL(n)      cout << fixed << setprecision(n);
#define rep(i,a,b)      for (ll i=a;i<b;i++)
#define repr(i,a,b)     for (ll i=a-1;i>=b;i--)
#define bitcount(a)     (ll)__builtin_popcount(a)
#define lbnd            lower_bound
#define ubnd            upper_bound
#define mp              make_pair
#define ios             ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ordered_set     tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update>
#define trace(...)      __f(#__VA_ARGS__, __VA_ARGS__)

template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
    std::cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
    const char* comma = strchr(names + 1, ',');std::cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}

using namespace std;
using namespace __gnu_pbds;

/*----------------------Graph Moves----------------*/
//const int fx[]={+1,-1,+0,+0};
//const int fy[]={+0,+0,+1,-1};
//const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};   // Kings Move
//const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};  // Kings Move
//const int fx[]={-2, -2, -1, -1,  1,  1,  2,  2};  // Knights Move
//const int fy[]={-1,  1, -2,  2, -2,  2, -1,  1}; // Knights Move
/*------------------------------------------------*/

//primes for hashing 937,991,1013,1409,1741

void solve() {
    ll n;
    cin>>n;
    ll meow=ceil(n/1000.0);
    cout<<meow*1000 - n<<endl;
}

signed main() {
    ios
    ll test=1;
    //cin>>test;
    while (test--) solve();
    return 0;
}

Measured memory_bytes: 3756
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

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

n,m=map(int,input().split())
e=[list(map(int,input().split())) for _ in range(m)][::-1]
u=UnionFind(n)
tmp=n*(n-1)//2
ans=[]
for a,b in e:
    ans.append(tmp)
    a,b=a-1,b-1
    if u.same(a,b):
        continue
    tmp-=u.size(a)*u.size(b)
    u.union(a,b)
print(*ans[::-1],sep='\n')

Measured memory_bytes: 35388
from sys import stdin
from itertools import combinations


def solve(nums):
    *positions, k = nums
    fst, last = positions[0], positions[-1]
    return abs(fst - last) <= k


def main():
    nums = [int(l) for l in stdin.readlines()]
    ans = solve(nums)
    print('Yay!' if ans else ':(')

if __name__ == '__main__':
    main()

Measured memory_bytes: 3060
#include<iostream>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>//min,max,swap,rand,reverse,sort,lower_bound
#include<functional>
#include<vector>
#include<list>
#include<map>
#include<tuple>
#include<cmath>//abs, sin, cos
#include<bitset>
using namespace std;

int main()
{
	int N, t, maxi=0;
	vector<int> A, A_copy;
	cin >> N;
	for (int i = 0; i < N; i++) {
		cin >> t;
		A_copy.push_back(t);
	}
	int first, second;
	A = A_copy;
	sort(A.begin(), A.end());
	reverse(A.begin(), A.end());
	first = A[0];
	second = A[1];

	for (int i = 0; i < N; i++) {
		if (A_copy[i] == first)
			cout << second << endl;
		else
			cout << first << endl;
	}

	return 0;
}

Measured memory_bytes: 4596
import java.io.*;
import java.util.*;

//solution classes here

public class Main {

    //main solution here

    static Scanner sc = new Scanner(System.in);
    static PrintWriter out = new PrintWriter(System.out);

    public static void main(String[] args) throws IOException {
        long k = sc.nextLong();
        int n = sc.nextInt();
        long a[] = new long[n];
        for(int i=0;i<n;i++)
            a[i]=sc.nextLong();
        long diff[] = new long[n];
        for(int i=0;i<n-1;i++) {
            diff[i]=a[i+1]-a[i];
        }
        diff[n-1] = k+a[0]-a[n-1];
        Arrays.sort(diff);
        long sum=0;
        for(int i=0;i<n-1;i++)
            sum+=diff[i];
        out.println(sum);


        out.flush();
        out.close();
    }

    //solution functions here


    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(FileReader fileReader) {
            br = new BufferedReader(fileReader);
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

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

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public boolean ready() throws IOException {
            return br.ready();
        }
    }
}

/* *****************************************************************************************************************************
 * I'M NOT IN DANGER, I'M THE DANGER!!!
 * *****************************************************************************************************************************
 */

Measured memory_bytes: 48084