akhauriyash/Code-Regression huggingface dataset:
//http://qa->itmedia->co->jp/qa9016289->html

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct _pt{
    float x;
    float y;

    struct _pt *n;
};
typedef struct _pt point;

int koch( point *p ){

    
    point *p1 = p;
    point *p2 = p->n;


    point *pa, *pb, *pc;

    pa = (point*)malloc(sizeof(point));
    pb = (point*)malloc(sizeof(point));
    pc = (point*)malloc(sizeof(point));

    p1->n=pa; pa->n=pc; pc->n=pb; pb->n=p2;

    pa->x = (p1->x*2+p2->x)/3; pa->y = (p1->y*2+p2->y)/3;
    pb->x = (p1->x+p2->x*2)/3; pb->y = (p1->y+p2->y*2)/3;
    
    //printf( "(%.2f,%.2f) ",  pa->x, pa->y);
    //printf( "(%.2f,%.2f)\n",  pb->x, pb->y);

    float ab = sqrt( pow(pa->x-pb->x,2) + pow(pa->y-pb->y,2) ); 
    float c = atan2((pb->y-pa->y),(pb->x-pa->x));
    //printf( " ab = %f\n", ab );
    //printf( " c = %f\n", c );
        
    //printf( " %.2f %.2f\n", cos(c), sin(c) );
    //printf( " %.2f %.2f\n", sqrt(3*cos(c)), sqrt(3*sin(c)) );
    
    pc->x = pa->x + ab*(cos(c)-sqrt(3)*sin(c))/2;
    pc->y = pa->y + ab*(sin(c)+sqrt(3)*cos(c))/2;
    //printf( " (%.2f,%.2f)\n", pc->x, pc->y );

    return 0;
}




int main(){

    int n, i;
    point *pt, *pt1, *pt2, *node;

    pt = (point*)malloc(sizeof(pt));
    node = pt;
    pt->x=0; pt->y=0;
    pt->n = (point*)malloc(sizeof(pt));
    pt = pt->n;
    pt->x=100; pt->y=0; pt->n=NULL;

    scanf( "%d", &n );



    for( i=0; i<n; i++ ){
        pt1 = node;
        while( pt1->n != NULL ){
            pt2 = pt1->n;
            koch( pt1 );
            pt1 = pt2;
        }
    }
    

    while( node != NULL ){

        printf( "%f %f\n", node->x, node->y );

        pt = node->n;
        free(node);
        node = pt;
    }

}


Measured memory_bytes: 2200
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;

internal class Program
{
    private static void Main(string[] args)
    {
        var N = int.Parse(Console.ReadLine());
        var array = Console.ReadLine().Split(' ').Select(int.Parse).OrderBy(x => x).ToList();
        int k = N / 2;
        if (N % 2 == 1 && array[0] != 0)
            k = -1;
        for (int i = N % 2; i < N; i += 2)
            if (array[i] != i + 1 || array[i + 1] != i + 1)
                k = -1;
        var ret = k == -1 ? 0 : BigInteger.ModPow(2, k, 1000000007);
        Console.WriteLine(ret);
    }
}

Measured memory_bytes: 12888
#include<iostream>
#include<string>
#include<vector>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include<cmath>
#include<map>
#include<functional>
#include<queue>
#include<stack>
#include<set>
using namespace std;

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

Measured memory_bytes: 1160
# -*- coding: utf-8 -*-
class BinaryHeap:
    def __init__(self, ary):
        self.nodes = []
        for i, key in enumerate(ary):
            id = i + 1
            parent = id // 2
            if parent:
                parent_key = ary[parent - 1]
            else:
                parent_key = None
            left = 2 * id
            right = 2 * id + 1
            if left <= len(ary):
                left_key = ary[left - 1]
            else:
                left_key = None
            if right <= len(ary):
                right_key = ary[right - 1]
            else:
                right_key = None
            self.nodes.append(Node(id, key, parent_key, left_key, right_key))

    def print(self):
        for node in self.nodes:
            print('node {}: key = {}, '.format(node.id, node.key), end='')
            if type(node.parent_key) == int:
                print('parent key = {}, '.format(node.parent_key), end='')
            if type(node.left_key) == int:
                print('left key = {}, '.format(node.left_key), end='')
            if type(node.right_key) == int:
                print('right key = {}, '.format(node.right_key), end='')
            print()


class Node:
    def __init__(self, id, key, parent_key, left_key, right_key):
        self.id = id
        self.key = key
        self.parent_key = parent_key
        self.left_key = left_key
        self.right_key = right_key


if __name__ == '__main__':
    H = int(input())
    ary = [int(_) for _ in input().split()]
    bh = BinaryHeap(ary)
    bh.print()



Measured memory_bytes: 5768
#include <bits/stdc++.h>
#define _GLIBCXX_DEBUG

using namespace std;
typedef long long ll;

#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define REP(a, b, m) for (ll a = (ll)(b); a < (ll)(m); a++)

int main()
{
    int n, l;
    cin >> n >> l;
    vector<string> s(n);
    rep(i, n)
    {
        cin >> s[i];
    }
    sort(s.begin(), s.end());
    rep(i, n)
    {
        cout << s[i];
    }
    cout << endl;
}

Measured memory_bytes: 256
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <set>
#include <map>
using namespace std;

#define REP(i, a, b) for (int i = (a), i##_end_ = (b); i < i##_end_; ++i)
#define MP make_pair
#define PB push_back
#define SZ(x) (int((x).size()))
#define ALL(x) (x).begin(), (x).end()
#define X first
#define Y second
template<typename T> inline bool chkmin(T &a, const T &b) { return a > b ? a = b, 1 : 0; }
template<typename T> inline bool chkmax(T &a, const T &b) { return a < b ? a = b, 1 : 0; }

template <class T>  
inline bool RD(T &ret) {  
        char c; int sgn;  
        if (c = getchar(), c == EOF) return 0;  
        while (c != '-' && (c<'0' || c>'9')) c = getchar();  
        sgn = (c == '-') ? -1 : 1 , ret = (c == '-') ? 0 : (c - '0');  
        while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');  
        ret *= sgn;  
        return 1;  
}  
template <class T>  
inline void PT(T x) {  
        if (x < 0) putchar('-') ,x = -x;  
        if (x > 9) PT(x / 10);  
        putchar(x % 10 + '0');  
}

const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> pii;
typedef long double LD;


const int N = 123;
int a[N];
int main()  {
	int n;
	RD(n);
	LL s = 0;
	LL ans = 1LL << 60;
	for(int i = 1; i <= n; i ++) RD(a[i]), s += a[i];
	for(int num = s / n - 2; num <= s / n + 2; num ++) {
		LL sum = 0;
		for(int i = 1; i <= n; i ++) sum += (num - a[i]) * (num - a[i]);
		ans = min(ans, sum);
	}
	cout << ans << endl;
}


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

int main(){
	char s[1001]={};
	cin>>s;
	int k=strlen(s);
	rep(i,k) cout<<s[i];
	if(s[k-1]=='s') cout<<"es"<<endl;
	else cout<<'s'<<endl;
}

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

int main() {
    cin.tie(0)->sync_with_stdio(false);

    int h, w;
    cin >> h >> w;

    vector<string> s(h);
    REP(i, h) cin >> s[i];

    int cnt = 0;
    REP(i, h) REP(j, w) {
        if (s[i][j] == '#')
            cnt++;
    }

    if (cnt == h + w - 1) cout << "Possible" << '\n';
    else cout << "Impossible" << '\n';
    return 0;
}


Measured memory_bytes: 256
use proconio::input;
use std::collections::HashMap;

#[derive(Hash, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
struct State {
    is_accept: bool,
    id: usize,
}

struct Automaton {
    states: HashMap<String, State>,
    transitions: HashMap<State, Box<dyn Fn(char) -> String>>,
    id: usize,
}

impl Automaton {
    fn add_states(&mut self, name: &str, is_accept: bool, transition: fn(char) -> String) {
        let state = State {
            is_accept,
            id: self.id,
        };
        self.id += 1;
        self.states.insert(name.to_string(), state);
        self.transitions.insert(state, Box::new(transition));
    }
    fn run(&self, s: String) -> bool {
        let mut current_state = *self.states.get("q0").unwrap();
        for c in s.chars() {
            let transition = self.transitions.get(&current_state).unwrap();
            let next_state_name = transition(c);
            current_state = *self.states.get(&next_state_name).unwrap();
        }
        current_state.is_accept
    }
}

fn transition_q0(c: char) -> String {
    if c == 'A' {
        return "q2".to_string();
    }

    "q1".to_string()
}
fn transition_q1(c: char) -> String {
    if c == 'A' {
        return "q3".to_string();
    }

    "q1".to_string()
}
fn transition_q2(c: char) -> String {
    if c == 'A' {
        return "q2".to_string();
    }

    "q3".to_string()
}
fn transition_q3(_c: char) -> String {
    "q3".to_string()
}

fn main() {
    input! {
        s: String,
    }

    let mut m = Automaton {
        states: HashMap::new(),
        transitions: HashMap::new(),
        id: 0,
    };

    m.add_states("q0", false, transition_q0);
    m.add_states("q1", false, transition_q1);
    m.add_states("q2", false, transition_q2);
    m.add_states("q3", true, transition_q3);

    if m.run(s) {
        println!("Yes");
    } else {
        println!("No");
    }
}

Measured memory_bytes: 2156
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
using namespace std;
 
#define mod 1000000007
#define FOR(x,to) for(int x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
#define long long long
inline int rei(){int x;cin>>x;return x;}
inline long rel(){long x;cin>>x;return x;}
inline string res(){string x;cin>>x;return x;}
//------------------------------------------------------- 
double DP[3000*3000];
void Calc(){
	int N = rei();
	DP[0] = 1;
	for(int i=0;i<N;i++){
		double prob;
		cin >> prob;
		for(int j=0;j<3000;j++){
			DP[(i+1)*3000+j] += DP[i*3000+j] * (1-prob);
			if(j != 2999){
				DP[(i+1)*3000+j+1] += DP[i*3000+j] * prob;
			}
		}
	}
	double sum = 0;
	for(int i=N/2+1;i<=N;i++){
		sum += DP[N*3000+i];
	}
	printf("%1.10lf\n",sum);
}
int main(int argc,char** argv){
	ios::sync_with_stdio(false), cin.tie(0);
	cout.tie(0); Calc(); return 0;
}

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

int main() {
    int l, r, d, ans;
    cin >> l >> r >> d;
    ans = 0;
    for (int i = l; i <= r; i++) {
        if (i % d == 0) {
            ans += 1;
        }
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 3592
/*input
1
1

*/
 
/*
                                                    ______________
                                                          |       )
                                                          |   )   /
                                                          |______/
                                                    |     |      \
                                                    |     |   )   \
                                                    |_____|_______)
 
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <ctime>
#include <cassert>
#include <complex>
#include <string>
#include <cstring>
#include <chrono>
#include <random>
#include <queue>
#include <bitset>
#include <iomanip>
#include <fstream>
#include <stack>

using namespace std;
 
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll , ll> PLL;
typedef long double ld;
 
#define pb push_back
#define all(c) c.begin(),c.end()
#define allr(c) c.rbegin(),c.rend()
int mod = 1000000007;
const int inf = 1034567891;
const ll LL_INF = 1234567890123456789ll;
#define PI 3.14159265
#define endl '\n'
#define F first
#define S second
#define debug(x) cout << #x << " = " << x << endl;
#define TRACE
 
#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cout << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');cout.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif
 
#define out(container) for (auto it : container) cout << it << " "; cout << endl;
 
 
template < typename T > T GCD(T a, T b)            { ll t; while(a) { t = a; a = b % a; b = t; } return b; }
template < typename T > string toString(T a)       { return to_string(a); }
template < typename T > void toInt(string s, T &x) { stringstream str(s); str >> x;}
inline int add(int x, int y){ x += y; if(x >= mod) x -= mod; return x;}
inline int sub(int x, int y){ x -= y; if(x < 0) x += mod; return x;}
inline int mul(int x, int y){ return (x * 1ll * y) % mod;}
inline int powr(int a, ll b){
  int x = 1 % mod;
  while(b){
    if(b & 1) x = mul(x, a);
    a = mul(a, a);
    b >>= 1;
  }
  return x;
}
inline int inv(int a){ return powr(a, mod - 2);}

int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  
  string str;
  getline(cin, str);
  int pos = 0;
  for (int i = 0; i < str.size(); i++) {
    if (str[i] == '+' || str[i] == '-') {
      pos = i;
      break;
    }
  }
  string word = str.substr(0, pos);
  ll a = 0; toInt(word, a);
  word = str.substr(pos + 1);
  ll b = 0; toInt(word, b);
  if (str[pos] == '+') cout << a + b << endl;
  else cout << a - b << endl;

  return 0;
}

Measured memory_bytes: 256
/*hello! guys~*/
#include<bits/stdc++.h>
using namespace std;
int main(){
  int i=0,n,a,b,c,t;
  int flag=1;
  cin>>t;
  while(t--)
  {
  	cin>>a;
  	if(a%2==0)
  	{
  		if(a%5!=0&&a%3!=0)
  		{
  			flag=0;
		  }
	  }
  } 
  if(flag)printf("APPROVED");
  else printf("DENIED");
  return 0;
} 


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

using namespace std;

int main() {
    long double ans=0;
    int n = 0;
    cin >> n;
    vector<int> x;
    vector<int> y;
    int a, b;
    for( int i=0; i<n; i++){
        cin >> a >> b;
        x.push_back( a );
        y.push_back( b );
    }
    
    for( int i=0; i<n; i++){
        for( int j=i+1; j < n ; j++){
            ans += sqrt( abs(x[i]-x[j])*abs(x[i]-x[j]) + abs(y[i]-y[j])*abs(y[i]-y[j]) );
        }
    }

    cout.precision(17);
    cout << ans*2/n;

    return 0;
}


Measured memory_bytes: 256
#include <iostream>
using namespace std;
int main() {
    int n, mini = 1e9, res = 0;
    cin >> n;
    for (int i = 0; i < n; ++i) {
        int a;
        cin >> a;
        mini = min(mini, a);
        if (a == mini)
            ++res;
    }
    cout << res << endl;
    return 0;
}

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

int main() {
  int A, B, C;
  scanf("%d%d%d", &A, &B, &C);

  if (A == B) {
    printf("%d", C);
  } else if (A == C) {
    printf("%d", B);
  } else {
    printf("%d", A);
  }
  return 0;
}


Measured memory_bytes: 256
// rust input macro: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}
 
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
 
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}
 
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
 
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
 
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
 
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
 
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
  input!{
    s : chars
  };
  if s[2]==s[3] && s[4]==s[5] {
    println!("Yes");
  }else{
    println!("No");
  }
}


Measured memory_bytes: 4352
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0545

"""
import sys
from sys import stdin
input = stdin.readline


def main(args):
    while True:
        n = int(input())
        m = int(input())
        if n == 0 and m == 0:
            break

        G = [[] for _ in range(n+1)]
        for _ in range(m):
            a, b = map(int, input().split())
            G[a].append(b)
            G[b].append(a)

        invitees = set()
        for f in G[1]:
            invitees.add(f)     #  ??´??\?????????
            for ff in G[f]:
                invitees.add(ff) #  ???????????????

        invitees.remove(1)      #  ????????????????????????????????????
        # print(invitees)
        print(len(invitees))


if __name__ == '__main__':
    main(sys.argv[1:])

Measured memory_bytes: 8332
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  int i;
  int a,b,d;
  cin >> a >> b;
  for(i = 1; i < 20; i++){
  d = b - a * i + (i - 1);  
  if(b == 1){
    cout << 0 << endl;
    break;
  }
  if(d <= 0) {
    cout << i << endl;
    break;
  }
}
}

Measured memory_bytes: 256
n, h = gets.chomp.split.map(&:to_i)
a = []
b = []
(0..(n - 1)).each do |i|
  a[i], b[i] = gets.chomp.split.map(&:to_i)
end

a_max = a.max
effective_b = b.select {|e| a_max <= e }
cnt = 0
flg = 0

effective_b.sort.reverse.each do |e|
  h -= e
  cnt += 1
  if h <= 0
    puts cnt
    flg = 1
    break
  end
end

if flg == 0
  if  (h % a_max) == 0
    cnt += h / a_max
  else
    cnt += (h / a_max) + 1
  end
  puts cnt
end

Measured memory_bytes: 5868
def dump(dp, max1, max2):
    return
    for i2 in range(max2 + 1):
        for i1 in range(max1 + 1):
            print('%4d' % dp[i1][i2], end='')
        print()
    print()

#inf = 999
inf = 1 << 60
s1 = input()
s2 = input()
max1 = len(s1)
max2 = len(s2)

# dp[i1][i2] = s1のi1文字目とs2のi2文字目までの編集距離
dp = [[inf] * (max2 + 2) for _ in range(max1 + 2)]

dp[0][0] = 0
dump(dp, max1, max2)

for i2 in range(0,max2+1):
    for i1 in range(0,max1+1):
        if i1 > 0:
            dp[i1][i2] = min(dp[i1][i2], dp[i1-1][i2] + 1)
        if i2 > 0:
            dp[i1][i2] = min(dp[i1][i2], dp[i1][i2-1] + 1)
        if i1 > 0 and i2 > 0:
            if s1[i1-1] == s2[i2-1]:
                dp[i1][i2] = min(dp[i1][i2], dp[i1-1][i2-1])
            else:
                dp[i1][i2] = min(dp[i1][i2], dp[i1-1][i2-1] + 1)
    dump(dp, max1, max2)

print(dp[max1][max2])



Measured memory_bytes: 42388
loop {
    n, m, s, g1, g2 = gets.split.map &:to_i
    break if n == 0
    cost = (1..n).map{ [Float::INFINITY] * n }  
    (0..n-1).each{|i| cost[i][i] = 0}
    m.times {
        i, j, c = gets.split.map &:to_i
        cost[i-1][j-1] = c
    }
    (0..n-1).each{|k|
        next_cost = (1..n).map{ Array.new(n) }  
        (0..n-1).each{|i|
            (0..n-1).each{|j|
                x = cost[i][j]
                y = cost[i][k] + cost[k][j]
                next_cost[i][j] = (x < y ? x : y)
            }   
        }       
        cost = next_cost
    }   
    p (0..n-1).map{|k| cost[s-1][k] + cost[k][g1-1] + cost[k][g2-1]}.min
}

Measured memory_bytes: 12332
#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;
  n %= 10;
  if(n==2||n==4||n==5||n==7||n==9){
    cout << "hon" << endl;
  }
  else if(n==3){
    cout << "bon" << endl;
  }
  else cout << "pon" << endl;

}


Measured memory_bytes: 3616
from collections import deque
n,qms = map(int, input().split())

que = deque([])
for i in range(n):
    name, value = input().split() # まずはデータを取り出して、それをDequeに入れこむ
    value = int(value)
    que.append([name,value])
i,t = 0,0

while len(que)>0:
    if que[0][1] > qms:
        name_rest,value_rest =que[0][0], que[0][1] - qms
        que.popleft()
        que.append([name_rest,value_rest])
        t += qms
    else:
        t += que[0][1]
        print(que[0][0],t)
        que.popleft()


Measured memory_bytes: 13304
#include <stdio.h>

int main(void){
	
	int n;
	scanf("%d",&n);
	
	int a[n];
	
	int i;
	
	for(i=0;i<n;i++){
		scanf("%d",&a[i]);
	}
	
	int j;
	int c=0; //count
	int t;
	
	for(i=0;i<n;i++){
		for (j = n-1; j > i; j--) {
			if( a[j] < a[j-1]) {
				t= a[j];
				a[j]=a[j-1];
				a[j-1]=t;
				c++;
				//printf("%d %d\n",a[j-1],a[j]);
			}
		}
	}

	for(j=0; j<n; j++) {
		if(j>0){
			printf(" ");
		}
		printf("%d",a[j]);
	}
	
	printf("\n%d\n",c);

	return 0;
}


Measured memory_bytes: 2100
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;


int main()
{
	int n,k,a[100005],dp[100005];
	cin>>n>>k;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	dp[1]=0;
	dp[2]=abs(a[2]-a[1]);
	for(int i=3;i<=n;i++)
	{
		int b=1000000000;
		for(int j=1;j<=k;j++)
		{
			if(i-j>=1)b=min(b,dp[i-j]+abs(a[i]-a[i-j]));
		}
		dp[i]=b;
	}
	cout<<dp[n]<<endl;
	return 0;
}

Measured memory_bytes: 1024
#include <set>
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <limits>
#include <map>
#include <numeric>

#define ll long long
using namespace std;
static ll imin = std::numeric_limits<ll>::min();
static ll imax = std::numeric_limits<ll>::max();
#define rep(i, n) for(int i = 0; i<n; ++i)
#define rep1(i, n) for(int i = 1; i<n; ++i)
#define rev_rep(i, n) for(int i = n - 1; i >= 0; --i)
#define range(a, i, b) for(int i = a; i <b; ++i)
#define dump(x) cout << #x << ":" << x << "\n";
#define all(v) v.begin(), v.end()
#define readl(N) ll N; cin >> N
#define readlv(N, vec) vector<ll> vec(N); rep(i, N){cin >> vec[i];}
#define greater_than [](ll l, ll r){return l > r;}
template<class T1, class T2>
std::ostream& operator << (std::ostream& os, std::map<T1, T2>& mp);
template<class T1, class T2>
std::ostream& operator << (std::ostream& os, std::pair<T1, T2>& pair);
template<class T>
std::ostream& operator << (std::ostream& os, std::vector<T>& vec);
template<class T1, class T2>
std::ostream& operator << (std::ostream& os, std::pair<T1, T2>& pair){
  os << '(' << pair.first << ',' << pair.second << ')';
  return os;
}

template<class T>
std::ostream& operator << (std::ostream& os, std::vector<T>& vec){
  std::size_t n = vec.size();
  if(n == 0){
    return os;
  }
  os << " ";
  for(int i = 0; i<n - 1; ++i){
    os << vec[i] << " ";
  }
  os << vec[n - 1];
  os << std::endl;
  return os;
}

template<class T1, class T2>
std::ostream& operator << (std::ostream& os, std::map<T1, T2>& mp){
  std::size_t n = mp.size();
  if(n == 0){
    return os;
  }
  os << " ";
  for(auto && x:mp){
    os << x << " ";
  }
  os << std::endl;
  return os;
}

template<class T>
std::ostream& operator << (std::ostream& os, std::set<T>& mp){
  std::size_t n = mp.size();
  if(n == 0){
    return os;
  }
  os << " ";
  for(auto && x:mp){
    os << x << " ";
  }
  os << std::endl;
  return os;
}

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


#ifndef BOOST_TEST_MAIN
int main(int const argc, char const** argv){
  readl(N);
  vector<ll> c(N), s(N), f(N);
  rep(i, N - 1){
    cin >> c[i] >> s[i] >> f[i];
  }


  rep(i, N - 1){
    ll clock = 0;
    range(i, j, N - 1){
      while(clock % f[j] != 0){
        clock++;
      }
      while(clock < s[j]){
        clock++;
      }
      clock += c[j];
    }
    // dump(i);
    cout << clock << endl;
  }
  cout << 0;
}
#endif


Measured memory_bytes: 256
use std::collections::BTreeMap;

const MOD: usize = 1_000_000_007;

fn main() {
    let mut sc = Scanner::new();
    let n: u64 = sc.read();

    let mut dp = BTreeMap::new();
    println!("{}", rec(n, n, &mut dp));
}

/// calculate the number of combinations of (u, v), which are satisfied u+v<=sum and u^v<=xor
fn rec(sum: u64, xor: u64, dp: &mut BTreeMap<(u64, u64), usize>) -> usize {
    if sum == 0 {
        return 1;
    }

    if dp.contains_key(&(sum, xor)) {
        return dp[&(sum, xor)];
    }

    let a1 = rec(sum >> 1, xor >> 1, dp); // both u and v are even
    let a2 = rec((sum - 1) >> 1, (xor - 1) >> 1, dp); // one is odd and another is even
    let a3 = if sum >= 2 {
        // both u and v are odd
        rec((sum - 2) >> 1, xor >> 1, dp)
    } else {
        0
    };

    let ans = (a1 + a2 + a3) % MOD;
    dp.insert((sum, xor), ans);
    return ans;
}

struct Scanner {
    ptr: usize,
    length: usize,
    buf: Vec<u8>,
    small_cache: Vec<u8>,
}

impl Scanner {
    fn new() -> Scanner {
        Scanner {
            ptr: 0,
            length: 0,
            buf: vec![0; 1024],
            small_cache: vec![0; 1024],
        }
    }

    fn load(&mut self) {
        use std::io::Read;
        let mut sum = std::io::stdin();
        self.length = sum.read(&mut self.buf).unwrap();
    }

    fn byte(&mut self) -> u8 {
        if self.ptr >= self.length {
            self.ptr = 0;
            self.load();
            if self.length == 0 {
                self.buf[0] = b'\n';
                self.length = 1;
            }
        }

        self.ptr += 1;
        return self.buf[self.ptr - 1];
    }

    fn is_space(b: u8) -> bool {
        b == b'\n' || b == b'\r' || b == b'\t' || b == b' '
    }

    fn read<T>(&mut self) -> T
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Debug,
    {
        let mut b = self.byte();
        while Scanner::is_space(b) {
            b = self.byte();
        }

        for pos in 0..self.small_cache.len() {
            self.small_cache[pos] = b;
            b = self.byte();
            if Scanner::is_space(b) {
                return String::from_utf8_lossy(&self.small_cache[0..(pos + 1)])
                    .parse()
                    .unwrap();
            }
        }

        let mut v = self.small_cache.clone();
        while !Scanner::is_space(b) {
            v.push(b);
            b = self.byte();
        }
        return String::from_utf8_lossy(&v).parse().unwrap();
    }
}


Measured memory_bytes: 4352
#include <bits/stdc++.h>
#define LL long long
#define PII pair<int,int>
#define PIL pair<int,LL>
#define PLI pair<LL,int>
#define PIII pair<int,PII>
#define PLL pair<LL,LL>
#define PLII pair<LL,PII>
#define VI vector<int>
#define VVI vector<VI>
#define VL vector<LL>
#define VVL vector<VL>
#define VPII vector<PII>
#define FF first
#define SS second
#define MP make_pair
#define PB push_back
#define all(x) x.begin(),x.end()
#define watch(x) cout<<(#x)<<" = "<<(x)<<'\n'
#define mset(a,v) memset(a,v,sizeof(a))
#define setp(x) cout<<fixed<<setprecision(x)
#define EPS 0.00000000001
#define PI acos(-1)
#define loop(i,b,n) for(int i=b;i<n;++i)
#define rev_loop(i,b,n) for(int i=b;i>=n;--i)
using namespace std;

const int MOD = 1e9 + 7;
const LL MX = 1e9;
const LL INF = 1e9;

int main()
{
    //ofstream out("output.txt");
    //ifstream in("input.txt");
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

    string s,t;
    cin>>s>>t;

    int n = s.length(), m = t.length(), ans = n;
    int c;

    for(int i = 0; i + m - 1 < n; ++i)
    {
        c = 0;
        for(int j = 0; j < m; ++j)
        {
            if(t[j] != s[i+j]) ++c;
        }
        ans = min(ans,c);
    }

    cout<<ans<<'\n';

    /*
    int t,n;
    cin>>t;
    while(t--)
    {
        cin>>n;
        int a[n];
        loop(i,0,n)
        {
            cin>>a[i];
        }
    }
    */

    /*
    int n;
    cin>>n;
    int a[n];
    loop(i,0,n)
    {
        cin>>a[i];
    }
    */

    /*
    cout<<ans<<'\n';

    if(f) cout<<"YES\n";
    else cout<<"NO\n";

    if(f) cout<<"Yes\n";
    else cout<<"No\n";
    */

    return 0;
}


Measured memory_bytes: 3640
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q,i,x,a;
    string s;
    map<string,int>m;
    map<string,int>::iterator it;
    cin>>q;
    for(i=0;i<q;i++){
        cin>>a;
        if(a==0){
           cin>>s>>x;
           m[s]=x;
        }
        else if(a==1){
            cin>>s;
            cout<<m[s]<<endl;
        }
        else if(a==2){
            cin>>s;
            m.erase(s);
        }
    }
    return 0;
}



Measured memory_bytes: 27804
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
class Solve{
    public Solve(){}
    StringBuilder sb;
    public static int Main(){
        new Solve().Run();
        return 0;
    }
    void Run(){
        sb = new StringBuilder();
        Calc();
        Console.Write(sb.ToString());
    }
    void Calc(){
        int N = int.Parse(Console.ReadLine());
        string[] str = Console.ReadLine().Split(' ');
        long[] A = new long[N];
        for(int i=0;i<N;i++){
            A[i] = int.Parse(str[i]);
        }
        long sum = 0;
        for(int i=0;i<N;i++){
            sum += A[i];
        }
        long count = 10000000000000000;
        long t = A[0];
        for(int i=1;i<N;i++){
            count = Math.Min(count,Math.Max(sum-2*t,2*t-sum));
            t += A[i];
        }
        sb.Append(count+"\n");
    }
}

Measured memory_bytes: 31964
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
using ll = long long;

struct UnionFind {
private:
  vector<ll> child, tree;
  vector<vector<ll>> list;

public:
  //頂点数v
  UnionFind(ll v) {
    tree.resize(v);
    list.resize(v);
    for(ll i = 0; i < v; i++) {
      tree[i] = i;
      list[i].push_back(i);
    }
  }

  //木の根を求める
  ll root(ll x) {
    if(x == tree[x]) {
      for(ll i = 0; i < child.size(); i++) {
        tree[child[i]] = x;
      }
      child.clear();
      return x;
    } else {
      child.push_back(x);
      return x = root(tree[x]);
    }
  }
  // xの所属するグループの大きさ
  ll size(ll x) { return list[root(x)].size(); }

  vector<ll> nodes(ll no) { return list[root(no)]; }

  // xとyの集合を合わせる
  bool unit(ll x, ll y) {
    x = root(x);
    y = root(y);
    if(x == y) {
      return false;
    }
    if(list[x].size() < list[y].size()) {
      swap(x, y);
    }
    for(int no : list[y]) {
      list[x].emplace_back(no);
    }
    tree[y] = x;
    return true;
  }

  // xとyが同じグループに所属するか
  bool isUnit(ll x, ll y) { return root(x) == root(y); }
};

int main() {
  int n, m;
  cin >> n >> m;
  UnionFind uf(n);
  for(int i = 0; i < m; i++) {
    int a, b;
    cin >> a >> b;
    a--;
    b--;
    uf.unit(a, b);
  }
  int maxi = 0;
  for(int i = 0; i < n; i++) {
    maxi = max(maxi, (int)uf.size(i));
  }
  cout << maxi << endl;
  return 0;
}

Measured memory_bytes: 22776
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
using namespace std;
#define REP(i,m,n) for(int i=(int)m ; i < (int) n ; ++i )
#define rep(i,n) REP(i,0,n)
typedef long long ll;
typedef pair<int,int> pint;
typedef pair<ll,int> pli;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
    using namespace std;
 
    int main(){
      int x,y;
      cin >> x >> y;
      int a[7]={1,3,5,7,8,10,12};
      int b[4]={4,6,9,11};
      bool flag=false;
      rep(i,7){
       rep(j,7){
        if(x==a[i] && y==a[j])flag=true; 
       }
      }
      rep(i,4){
       rep(j,4){
        if(x==b[i] && y==b[j])flag=true; 
       }
      }
      if(flag) cout << "Yes" << endl;
      else cout << "No" << endl;
      return 0;}

Measured memory_bytes: 256
void main()
{
    double l = rdElem!double;

    double eps = 1.0e-10;
    double ok = 0.0, ng = l;
    while (ng - ok > eps)
    {
        double m = (ok + ng) / 2.0;
        if (3.0 * m <= l) ok = m;
        else ng = m;
    }

    double result = ok * ok * ok;
    writefln("%.15f", result);
}

enum long mod = 10^^9 + 7;
enum long inf = 1L << 60;

T rdElem(T = long)()
if (!is(T == struct))
{
    return readln.chomp.to!T;
}

alias rdStr = rdElem!string;
alias rdDchar = rdElem!(dchar[]);

T rdElem(T)()
if (is(T == struct))
{
    T result;
    string[] input = rdRow!string;
    assert(T.tupleof.length == input.length);
    foreach (i, ref x; result.tupleof)
    {
        x = input[i].to!(typeof(x));
    }
    return result;
}

T[] rdRow(T = long)()
{
    return readln.split.to!(T[]);
}

T[] rdCol(T = long)(long col)
{
    return iota(col).map!(x => rdElem!T).array;
}

T[][] rdMat(T = long)(long col)
{
    return iota(col).map!(x => rdRow!T).array;
}

void rdVals(T...)(ref T data)
{
    string[] input = rdRow!string;
    assert(data.length == input.length);
    foreach (i, ref x; data)
    {
        x = input[i].to!(typeof(x));
    }
}

void wrMat(T = long)(T[][] mat)
{
    foreach (row; mat)
    {
        foreach (j, compo; row)
        {
            compo.write;
            if (j == row.length - 1) writeln;
            else " ".write;
        }
    }
}

import std.stdio;
import std.string;
import std.array;
import std.conv;
import std.algorithm;
import std.range;
import std.math;
import std.numeric;
import std.mathspecial;
import std.traits;
import std.container;
import std.functional;
import std.typecons;
import std.ascii;
import std.uni;
import core.bitop;

Measured memory_bytes: 256
nl = lambda: list(map(int, input().split()))
sl = lambda: input().split()
n = lambda: int(input())
s = lambda: input()

S = s()

left = set(list('abcdefghijklmnopqrstuvwxyz'))
for c in S:
    if c in left:
        left.remove(c)

if len(left) > 0:
    print(sorted(list(left))[0])
else:
    print('None')


Measured memory_bytes: 3188
#include <stdio.h>
int med3(int x, int y, int z) {
    if (x < y) {
        if (y < z) return y; else if (z < x) return x; else return z;
    } else {
        if (z < y) return y; else if (x < z) return x; else return z;
    }
}
int main(void){
    int N;
    int count = 0;
    scanf("%d", &N);
    int p[N];
    for(int i = 0; i< N; i++){
        scanf("%d", &p[i]);
    }
    for(int i = 0; i< N-2; i++){
        int m = med3(p[i], p[i+1], p[i+2]);
        if(m == p[i+1]) count += 1;
    }
    printf("%d\n", count);
    return 0; 
}

Measured memory_bytes: 128
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>	
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<queue>
#include<cstdio>
#include<sstream>
#include<iomanip>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
#define shosu(x) fixed<<setprecision(x)
using namespace std;
//kaewasuretyuui
typedef long long ll;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vp;
typedef vector<vp> vvp;
typedef pair<int,pii> pip;
typedef vector<pip>vip;
const double PI=acos(-1);
const double EPS=1e-8;
const int inf=1e8;
int gcd(int a,int b){
	return (b==0?a:gcd(b,a%b));
}
int main(){
	int a,b;
	while(cin>>a>>b,a+b){
		double q=sqrt(a);
		int c=1,d=1,e=1,f=inf;
		loop(i,1,b+1){
			int t=ceil(i/q);
			t--;
			if(q<(double)i/t&&(double)i/t<(double)f/e){
				f=i;e=t;
				int w=gcd(f,e);
				f/=w;t/=w;
			}
			t++;
			if(t!=0){
				if(q>(double)i/t&&(double)i/t>(double)d/c){
					d=i;c=t;
					int w=gcd(d,c);
					d/=w;c/=w;
				}
			}
		}
		cout<<f<<"/"<<e<<" "<<d<<"/"<<c<<endl;
	}
}

Measured memory_bytes: 1164
'use strict'

const main = (INPUT) => {
  const input = INPUT.split('\n')
  const N = input[0].split(' ')[0].split('').map(n => Number(n)).reverse()
  const D = input[1].split(' ').map(n => Number(n))
  const ary = []
  for (let i = 0; i <= 9; i++) {
    if (D.indexOf(i) == -1) {
      ary.push(i)
    }
  }
  let flag
  for (let i = 0; i < N.length; i++) {
    while (true) {
      if (ary.indexOf(N[i]) >= 0) {
        if (flag && i == N.length - 1) {
          for (let j = 0; j < i; j++) {
            N[j] = ary[0]
          }
          i = 0
          flag = false
          continue
        }
        break
      }
      N[i] = N[i] + 1
      flag = true
      if (N[i] >= 10) {
        if (i == N.length - 1) {
          N.push(1)
          N[i] = 0
        } else {
          N[i + 1] = N[i + 1] + 1
          N[i] = 0
        }
      }
    }
  }

  console.log(N.reverse().join(''))
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


Measured memory_bytes: 7372
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//Simple GUI Application
public class Main{

	class E{
		String name;
		int x1, y1, x2, y2, num;
		List<E> adj;
		public E(String name, int x1, int y1, int x2, int y2) {
			this.name = name;
			this.x1 = x1;
			this.y1 = y1;
			this.x2 = x2;
			this.y2 = y2;
			adj = new ArrayList<E>();
			num = -1;
		}
		boolean f(int x, int y){
			boolean hit =  x1<=x&&x<=x2&&y1<=y&&y<=y2;
			if(!hit)return hit;
			boolean here = true;
			for(E e:adj)if(e.f(x, y))here = false;
			if(!here)return true;
			System.out.println(name+" "+adj.size());
			return true;
		}
	}
	
	char[] s;
	int id;
	
	char get(){
		return s[id++];
	}
	
	E tag(){
		StringBuilder sb = new StringBuilder();
		char ch = get();
		while(ch!='>'){
			sb.append(ch);
			ch = get();
		}
		E r = new E(sb.toString(), val(), val(), val(), val());
		ch = get();
		while(true){
			if(ch=='/')break;
			id--;
			r.adj.add(tag());
			ch = get();
		}
		while(ch!='>')ch = get();
		id++;
		return r;
	}
	
	int val(){
		int x = 0;
		char ch = get();
		while(Character.isDigit(ch)){
			x = x*10 + ch-'0';
			ch = get();
		}
		return x;
	}
	
	void run(){
		Scanner sc = new Scanner(System.in);
		while(true){
			int n = sc.nextInt();
			if(n==0)break;
			s = (sc.next()+"$").toCharArray();
			id = 1;
			E e = tag();
			while(n--!=0)if(!e.f(sc.nextInt(), sc.nextInt()))System.out.println("OUT OF MAIN PANEL 1");
		}
	}
	
	public static void main(String[] args) {
		new Main().run();
	}
}

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

int main(){
    int n, a[1000];
    cin >> n;

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

    sort(a, a + n);

    cout << a[n-1] - a[0] << endl;

    return 0;
    
}

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

long long dp[101][100001];
long long solve(long long  arr[][2], long long  i, long long  n, long long  cr_w, long long  w)
{
    
    
    if(i==n)
        return dp[i][cr_w] = 0;
        
    if(dp[i][cr_w] !=-1)
        return dp[i][cr_w];
        
    long long  p = 0;
    if(cr_w+arr[i][0]<=w)
        p = arr[i][1] + solve(arr,i+1,n,cr_w+arr[i][0],w);
        
    long long  q =  solve(arr,i+1,n,cr_w,w);
    
    return dp[i][cr_w] = max(p,q);
}

int main() {
    
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    
    long long  n,w,i;
    cin >> n >> w;
    memset(dp,-1,sizeof(dp));
    long long  arr[n][2];
    
    for(i=0;i<n;i++)
        cin >> arr[i][0] >> arr[i][1];
    
    cout << solve(arr,0,n,0,w) << endl;
    
    
    
    return 0;
}
 

Measured memory_bytes: 79232
import sys
sys.setrecursionlimit(10**9)
mod = 10**9+7
N,K = map(int,input().split())
g = [[] for _ in range(N)]
for i in range(N-1):
    a,b = map(int,input().split())
    a -= 1
    b -= 1
    g[a].append(b)
    g[b].append(a)


ans = K
def rec(c,p):
    global ans
    if c == 0:
        for i in range(len(g[0])):
            ans *= K-i-1
            ans %= mod
        for v in g[c]:
            if v != p:
                rec(v,c)
    else:
        for i in range(len(g[c])-1):
            ans *= K-i-2
            ans %= mod
        for v in g[c]:
            if v != p:
                rec(v,c)


rec(0,0)
print(ans)

Measured memory_bytes: 87948
S = input()
Q = int(input())
Query = [input() for _ in range(Q)]
flag = True
s = "!"
for i in range(Q):
    if Query[i][0] == "1":
        if flag:
            flag = False
        else:
            flag = True
    else:
        if Query[i][2] == '1':
            if flag:
                s = Query[i][4] + s
            else:
                s = s + Query[i][4]
        else:
            if flag:
                s = s + Query[i][4]
            else:
                s = Query[i][4] + s
ans = s.replace("!", S)
if flag:
    print(ans)
else:
    print(ans[::-1])

Measured memory_bytes: 17032
n = int(input())
li = []
c = 1
for i in range(n):
    w = input()
    if w in li:
        c = 0
        
    else:
        li.append(w)

if c == 1:
    for i in range(1,n):
        if li[i - 1][-1] != li[i][0]:
            c = 0
            break
        else:
            c = 1
        
if c == 0:
    print("No")
else:
    print("Yes")

Measured memory_bytes: 3060
#include <algorithm>
#include <iostream>
#include <string>
#include <random>
#include <cassert>
#include <cstring>
#include <chrono>
#include <set>
#include <map>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;

int main()
{
  ll a, b, c;
  cin >> a >> b >> c;
  for (int result = 0; result < 1000; ++result) {
    if (a % 2 || b % 2 || c % 2) {
      cout << result << endl;
      return 0;
    }
    ll aa = a / 2;
    ll bb = b / 2;
    ll cc = c / 2;
    a = bb + cc;
    b = aa + cc;
    c = aa + bb;
  }
  cout << - 1 << endl;
  return 0;
}


Measured memory_bytes: 256
s=input()
sf=int(s[:2])
sl=int(s[2:])
#print(int(sf)+int(sl))
if (1<= sf <=12 and 1<=sl <=12):
  print("AMBIGUOUS")
elif 1<= sf <=12 and (sl==0 or 12<sl):
  print("MMYY")
elif 1<= sl <=12 and (sf==0 or 12<sf):
  print("YYMM")
else:
  print("NA")

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

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)

using ll = long long;
using ld = long double;
ll INF = LLONG_MAX;

using vi = vector<int>;
using vll = vector<ll>;
using pii = pair<int, int>;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }
	
	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);
	
	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) { 
		pr(t); pr(ts...); 
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) { 
		pr("{",x.f,", ",x.s,"}"); 
	}
	template<class T> void pr(const T& x) { 
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0; 
		pr("}");
	}
	
	void print() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void print(const T& t, const Ts&... ts) { 
		pr(t); if (sizeof...(ts)) pr(" "); print(ts...); 
	}
}

using namespace output;

int main() {
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	int K; cin >> K;
	ll sum = 0;
	FOR(i, 1, K+1) FOR(j, 1, K+1) FOR(k, 1, K+1) {
		sum += __gcd(i, __gcd(j, k));
	}
	print(sum);
}

Measured memory_bytes: 3644
#include <iostream>
#include <iomanip> // << fixed << precision(10)
#include <vector>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <cmath>
#include <algorithm>
using namespace std;

#define FOR(i,s,t) for(int i=s;i<t;i++)
#define REP(i,n) FOR(i,0,n)
#define PRINT(s) cout << s << "\n"
#define SORT(A) sort(A.begin(), A.end())
#define EACHPRINT(A, T) for_each(begin(A), end(A), [&](T i){ cout << i << " "; });cout << "\n"
#define MOD 1000000007

typedef long lint;
typedef pair<lint, lint> P;
bool lessPair(const P& l, const P& r){return l.second < r.second;}
bool morePair(const P& l, const P& r){return l.second > r.second;}

vector<lint> TopSort(lint N, vector<P> edges) {
  vector<lint> in_degree(N);
  vector<vector<lint>> adj(N);
  vector<lint> res(N);

  REP(i, edges.size()) {
    auto edge = edges[i];
    in_degree[edge.second]++;

    adj[edge.first].push_back(edge.second);
  }
  queue<lint> Q;

  lint idx = 0;

  REP(i, N) {
    if(in_degree[i] == 0) {
      Q.push(i);
    }
  }


  while(!Q.empty()) {
    lint i = Q.front();
    Q.pop();
    res[i] = idx++;
    REP(j, adj[i].size()) {
      auto k = adj[i][j];
      in_degree[k]--;
      if(in_degree[k] == 0) {
        Q.push(k);
      }
    }
  }

  return res;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    lint N; cin >> N;
    lint M; cin >> M;
    vector<P> edges(N+M);

    REP(i, N+M) {
      lint x,y; cin >> x; cin >> y;
      edges[i] = P(x-1, y-1);
    }

    auto top = TopSort(N, edges);

    vector<lint> in_degree(N);
    vector<vector<lint>> rev_adj(N);

    REP(i, edges.size()) {
      auto edge = edges[i];
      in_degree[edge.second]++;

      rev_adj[edge.second].push_back(edge.first);
    }

    REP(i, N) {
      if(in_degree[i] == 0) {
        PRINT(0);
        continue;
      }

      lint res = rev_adj[i][0];
      
      FOR(j, 1, rev_adj[i].size()) {
        lint n = rev_adj[i][j];
        if(top[n] > top[res]){
          res = n;
        }
      }
      PRINT(res+1);
    }
    
    return 0;
}


Measured memory_bytes: 10368
using System;
namespace csharptest
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] h = new int[100000];
            int[] w = new int[100000];
            int count;
            string[] str = Console.ReadLine().Split(' ');
            for (count = 0; str[0] != "0" && str[1] != "0"; count++)
            {
                h[count] = int.Parse(str[0]);
                w[count] = int.Parse(str[1]);
                str = Console.ReadLine().Split(' ');
            }
            for (int n = 0; n < count; n++)
            {
                for (int H = 0; H < h[n]; H++)
                {
                    if (H % 2 == 0)
                    {
                        for (int W = 0; W < w[n]; W++)
                        {
                            if (W % 2 == 0)
                            {
                                Console.Write("#");
                            }
                            else
                            {
                                Console.Write(".");
                            }
                        }
                    }
                    else
                    {
                        for (int W = 0; W < w[n]; W++)
                        {
                            if (W % 2 == 0)
                            {
                                Console.Write(".");
                            }
                            else
                            {
                                Console.Write("#");
                            }
                        }
                    }
                    Console.WriteLine();
                }
                Console.WriteLine();
            }
        }
    }
}

Measured memory_bytes: 6096