akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define F first
#define S second
#define pb push_back
mt19937 rnd;

struct segment_tree {
    static const int N = 2e5 + 10;
    int t[4 * N];
    int merge(int x, int y) {
        return max(x, y);
    }
    void update(int pos, int val, int v = 1, int tl = 1, int tr = N - 1) {
        if (tl > tr || tl > pos || pos > tr) return;
        if (tl == tr) {
            t[v] = val;
            return;
        }
        int tm = (tl + tr)/2;
        update(pos, val, v + v, tl, tm);
        update(pos, val, v + v + 1, tm + 1, tr);
        t[v] = merge(t[v + v], t[v + v + 1]);
    }
    int get(int l, int r, int v = 1, int tl = 1, int tr = N - 1) {
        if (tl > tr || l > r || tl > r || l > tr) return 0;
        if (l <= tl && tr <= r) {
            return t[v];
        }
        int tm = (tl + tr)/2;
        return merge(get(l, r, v + v, tl, tm), get(l, r, v + v + 1, tm + 1, tr));
    }
} t;

void delete_copies(vector<int>& a) {
    sort(a.begin(), a.end());
    a.erase(unique(a.begin(), a.end()), a.end());
}

const int N = 2e5 + 10;
int a[N];
vector<int> all;
map<int, int> mp;
vector<int> g[N];
int ans[N];

void dfs(int v, int p) {
    int pos = mp[a[v]];
    int rem = t.get(pos, pos);
    t.update(pos, t.get(1, pos - 1) + 1);
    ans[v] = t.get(1, N - 1);
    for (int to : g[v]) {
        if (to != p) {
            dfs(to, v);
        }
    }
    t.update(pos, rem);
}

int main() {
    ios_base::sync_with_stdio(0); cin.tie(0);
#ifdef LOCAL
    freopen("input.txt", "r", stdin);
#endif

    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        all.pb(a[i]);
    }
    delete_copies(all);
    for (int i = 0; i < all.size(); i++) {
        mp[all[i]] = i + 1;
    }
    for (int i = 1; i <= n - 1; i++) {
        int u, v;
        cin >> u >> v;
        g[u].pb(v);
        g[v].pb(u);
    }
    dfs(1, 1);
    for (int i = 1; i <= n; i++) {
        cout << ans[i] << "\n";
    }

#ifdef LOCAL
    cerr << "\nTime elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
#endif
    return 0;
}


Measured memory_bytes: 41204
from collections import defaultdict
d = defaultdict(int)
n = int(input())
for i in range(n):
  s = input()
  d[s] += 1
d = dict(d)
d = sorted(d.items(), key=lambda x:x[1], reverse=True)
max_s = d[0][1]
l = [d[i][0] for i in range(len(d)) if d[i][1] == max_s]
l.sort()
for s in l:
  print(s)

Measured memory_bytes: 43480
/*
  
  Author: Arnab Sinha
	
  ███████╗██╗  ██╗███████╗██████╗         ██╗      ██████╗  ██████╗██╗  ██╗███████╗██████╗  █████╗  █████╗ 
  ██╔════╝██║  ██║██╔════╝██╔══██╗        ██║     ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔══██╗
  ███████╗███████║█████╗  ██████╔╝        ██║     ██║   ██║██║     █████╔╝ █████╗  ██║  ██║╚██████║╚██████║
  ╚════ █║██╔══██║██╔══╝  ██╔══██╗        ██║     ██║   ██║██║     ██╔═██╗ ██╔══╝  ██║  ██║ ╚═══██║ ╚═══██║
  ███████║██║  ██║███████╗██║  ██║███████╗███████╗╚██████╔╝╚██████╗██║  ██╗███████╗██████╔╝ █████╔╝ █████╔╝
  ╚══════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚══════╝╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝╚═════╝  ╚════╝  ╚════╝                                                                                                        
*/
 
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define li long long int
#define ld long long double
#define all(v) v.begin(),v.end()
#define sort(a) sort(all(a))
#define rev(a) reverse(all(a))
#define pb push_back
#define INF 1e18+10
#define MINF -1e18-10
#define rep(i,a,b) for(li i=a;i<b;i++)
#define vli vector<li>
#define MAXN 1e5+10
const li mod = 1e9+7;
using namespace std;
 
li power(li a, li b) { a%=mod; li ret = 1; while(b){ if(b&1) ret*=a; a*=a;; if(ret>=mod) ret%=mod; if(a>=mod) a%=mod; b>>=1; } return ret; }
 
template <class T> void read(T& x){
	cin>>x;
}
 
template <class T, class... U> void read(T& x, U&... u){
	read(x);
	read(u...);
}
 
template <class A> void read(vector<A>& v){
	for(auto &it:v)
		read(it);
}
 
template <class A> void print(A x){
	cout<<x;
}
 
template <class A> void printl(A x){
	cout<<x<<endl;
}
 
template <class A> void print(vector<A>& v)
{
	for(auto &it:v){
		print(it);
		cout<<' ';
	}
	cout<<'\n';
}
 
void solve()
{
	li x;
	cin>>x;

	if(x==0)
		cout<<1<<endl;
	else
		cout<<0<<endl;
}

 
int main()
{
	IOS;
 
 	solve();
 
	return 0;
}

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

const int MAXN = 100005, B = 20;
vector<int> gra[MAXN];
int f[MAXN][B], n, ans;

void dfs(int u, int fa) {
	for (int v : gra[u]) if (v != fa) {
		dfs(v, u);
		for (int i = 0; i < B; i++)
			f[u][i] += f[v][i];
	}
	int p = 0;
	for (int i = B - 1; ~i; i--)
		if (f[u][i] > 1) { p = i; break; }
	while (f[u][p]) ++p;
	f[u][p] = 1;
	for (int i = 0; i < p; i++) f[u][i] = 0;
	chkmax(ans, p);
}

int main() {
	scanf("%d", &n);
	for (int i = 1; i < n; i++) {
		int u, v; scanf("%d%d", &u, &v);
		gra[u].push_back(v), gra[v].push_back(u);
	}
	dfs(1, 0);
	printf("%d\n", ans);
	return 0;
}

Measured memory_bytes: 19200
import java.math.BigInteger;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {
	static long modpow(long a, long n, long mod) {
	    long res = 1;
	    while (n > 0) {
	        if ((n & 1) != 0) res = res * a % mod;
	        a = a * a % mod;
	        n >>= 1;
	    }
	    return res;
	}
	static long modinv(long a, long mod) {
	    return modpow(a, mod - 2, mod);
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int A[] = new int[N];
		int M = 0;
		for(int i = 0 ; i < N ; ++i){
			A[i] = sc.nextInt();
			M = Math.max(M, A[i]);
		}
		int ps[] = new int[M + 1];
		for(int i = 0 ; i < N ; ++i){
			int a = A[i];
			for(int p = 2 ; p * p <= a ; ++p){
				int cnt = 0;
				while(a % p == 0){
					a = a / p;
					++cnt;
				}
				ps[p] = Math.max(ps[p], cnt);
			}
			if(a != 1){
				ps[a] = Math.max(ps[a], 1);
			}
		}
		// lcm
		long L = 1;
		long MOD = 1000000007;
		for(int i = 0 ; i < ps.length ; ++i){
			if(ps[i] > 0){
				L = (L * modpow(i , ps[i], MOD)) % MOD;
			}
		}
		long ret = 0;
		for(int i = 0 ; i < N ; ++i){
			int a = A[i];
			long ainv = modinv(a, MOD);
			long b = L * ainv;
			ret = (ret + b) % MOD;
		}
		System.out.println(ret);
	}
}


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

int main() {
  int x1, y1, x2, y2;
  cin >> x1 >> y1 >> x2 >> y2;
  
  int x3, y3, x4, y4;
  int a = x2 - x1, b = y2 - y1;
  
  x3 = x2 - b;
  y3 = y2 + a;
  x4 = x3 - a;
  y4 = y3 - b;
  cout << x3  << " " << y3 << " " << x4 << " "  << y4 << endl;
}

Measured memory_bytes: 256
s = input()

if len(s) == 2:
    if s[0] == s[1]:
        print(1, 2)
    else:
        print(-1, -1)
else:
    for i in range(len(s)-2):
        tmp = s[i:i+3]
        if tmp.count(tmp[0]) >= 2:
            print(i+1, i+3)
            quit()
    
    print(-1, -1)

Measured memory_bytes: 3188
class UnionFind
  def initialize(size)
    @rank = Array.new(size, 0)
    @parent = Array.new(size, &:itself)
  end

  def unite(id_x, id_y)
    x_parent = get_parent(id_x)
    y_parent = get_parent(id_y)
    return if x_parent == y_parent

    if @rank[x_parent] > @rank[y_parent]
      @parent[y_parent] = x_parent
    else
      @parent[x_parent] = y_parent
      @rank[y_parent] += 1 if @rank[x_parent] == @rank[y_parent]
    end
  end

  def get_parent(id_x)
    @parent[id_x] == id_x ? id_x : (@parent[id_x] = get_parent(@parent[id_x]))
  end

  def same_parent?(id_x, id_y)
    get_parent(id_x) == get_parent(id_y)
  end
end

n, m = gets.strip.split.map(&:to_i)
ps = gets.strip.split.map(&:to_i)
xy = readlines.map {|line| line.strip.split.map(&:to_i) }

uf = UnionFind.new(n+1)

xy.each do |x, y|
  uf.unite(x,y)
end

p (1..n).to_a.select {|i| uf.same_parent?(i, ps[i-1]) }.length


Measured memory_bytes: 21172
<?php

class Simulator
{
    public $queue = array();
    public $n_processes;
    public $quantum;

    public function __construct()
    {
        fscanf(STDIN, "%s %d", $this->n_processes, $this->quantum);
        $n = $this->n_processes;
        while ($n > 0) {
            fscanf(STDIN, "%s %d", $name, $time);
            $this->queue[] = [
                'name' => $name,
                'time' => $time
            ];
            $n -= 1;
        }
    }

    public function executeProcess()
    {
        $time_count = 0;
        while (count($this->queue) > 0) {
            $queue_rest = array();
            for ($i = 0; $i < count($this->queue); $i++) {
                $process = $this->queue[$i];
                if ($process['time'] - $this->quantum <= 0) {
                    $time_count += $process['time'];
                    echo $process['name'] . ' ' . $time_count . "\n";
                    continue;
                } else {
                    $process['time'] -= $this->quantum;
                    $queue_rest[] = $process;
                    $time_count += $this->quantum;
                }
            }
            $this->queue = $queue_rest;
        }
    }
}

$answer = new Simulator();
$answer->executeProcess();


Measured memory_bytes: 49116
//          ★★ ASHWINI SHARMA ★★ 
#include <bits/stdc++.h>
using namespace std;
 
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define fr(i,a,b) for (int i = (a), _b = (b); i <= _b; i++)
#define frr(i,a,b) for (int i = (a), _b = (b); i >= _b; i--)
#define rep(i,n) for (int i = 0, _n = (n); i < _n; i++)
#define repr(i,n) for (long long i = (n) - 1; i >= 0; i--)
#define foreach(it,ar) for ( typeof(ar.begin()) it = ar.begin(); it != ar.end(); it++ )
#define ull unsigned long long int
#define ll long long int
#define ui unsigned int
#define pb push_back
 
#define PI 3.1415926535897932385
#define INF 1e9
#define EPS 1e-7
#define MAXN 1000000005
#define MOD 1000000007 
                              //          ★★ ASHWINI SHARMA ★★      
ll gcd(ll a, ll b) 
{ 
    if (a == 0) 
        return b; 
    return gcd(b % a, a); 
} 
ll exp(ll x, ll y, ll p)
{
    ll res = 1;   
    x = x % p;  
    while (y > 0)
    {
        if (y & 1)    
            res = (res*x) % p;
        y = y>>1;     
        x = (x*x) % p; 
    }
    return res;
}



int main() {
   
    fastio;
    int d, t, s;
    cin >> d >> t >> s;
    int x = d / s;
    if(x < t)
    {
        cout << "Yes";
    }
    else if(x == t)
    {
        if(x * s == d)
            cout << "Yes";
        else
            cout << "No";
    }
    else
        cout << "No";
    




    return 0; 
}

Measured memory_bytes: 3648
"use strict";

var input = require("fs").readFileSync("/dev/stdin", "utf8");
var cin = input.split(/ |\n/),
    cid = 0;

function next() {
    return +cin[cid++];
} // number一個取得
function nextstr() {
    return cin[cid++];
} // 文字列一個取得
function nextbig() {
    return BigInt(cin[cid++]);
} // BigInteger一個取得
// 長さnの配列として取得。aは文字列フラグ
function nexts(n, a) {
    return a ? cin.slice(cid, cid += n) : cin.slice(cid, cid += n).map(a => +a);
}
// 長さnのBigInt配列として取得。
function nextsbig(n) {
    return cin.slice(cid, cid += n).map(a => BigInt(a));
}
// w個ずつを組にして長さhの配列。aは文字列フラグ。
function nextm(h, w, a) {
    var r = [],
        i = 0;
    if (a)
        for (; i < h; i++) r.push(cin.slice(cid, cid += w));
    else
        for (; i < h; i++) r.push(cin.slice(cid, cid += w).map(a => +a));
    return r;
}
// 多次元配列。v,a1,a2,a3 なら、3次元。[[値vで長さa3の配列]をa2個並べた配列]をa1個並べた配列。
function xArray(v) {
    var a = arguments,
        l = a.length,
        r = "Array(a[" + --l + "]).fill().map(x=>{return " + v + ";})";
    while (--l) r = "Array(a[" + l + "]).fill().map(x=>" + r + ")";
    return eval(r);
}


console.log(main().toString());

function main() {
    let n = nextstr().split("");
    let obj = {}
    for (let c of n) {
        obj[c] = true;
    }
    let dic = "abcdefghijklmnopqrstuvwxyz".split("")
    for(let c of dic){
        if(!obj[c]) return c;
    }

    return "None"
}

Measured memory_bytes: 15796
object Main extends App {
  
  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt()
  val a = Array.fill(n)(sc.nextInt())
  val max = a.max
  println(calc(a, 0, 1, 0))
  
  def calc(list :Array[Int], i: Int, t: Int, acc: Int): Int = {
    
    if (i >= list.length) {
      if (acc == list.length) {
        -1
      } else {
        acc
      }
    } else if (list(i) == t) {
      calc(list, i+1, t+1, acc)
    } else {
      calc(list, i+1, t, acc+1)
    }
  }
}

Measured memory_bytes: 60988
#include "bits/stdc++.h"

using namespace std;

#define ll long long
#define vi  vector<int>
#define vvi vector<vi>
#define pi  pair<int,int>
#define mp  make_pair
#define pb  push_back
#define MOD 1e9 + 7
#define PAI  3.1415
#define all(x) (x).begin(),(x).end()
#define chmax(x,y) x = max(x,y)
#define chmin(x,y) x = min(x,y)
#define pr(x) cout << x << endl
#define Endl endl
#define rep(i,n) for(int i = 0 ; i < n; i++)

const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
const int ddx[8] = {-1,0,1,-1,1,-1,0,1};
const int ddy[8] = {-1,-1,-1,0,0,1,1,1};
const int inf = 99999999;
const ll linf = 1LL << 62;

ll gcd(ll a,ll b){
  if(a < b)swap(a , b);
  if(a % b == 0) return b;
  else gcd(b, a%b);
}

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

struct UnionFind {
  vi par; //par[i] : iの親番号（例）par[3] = 2 : 3の親は2

  UnionFind(int N) : par(N) { //最初は全てが根として初期化
    rep(i,N) par[i] = i;
  }

  int root(int x){ //データxが属する木の根を再帰で得る : root(x) = {xの木の根}
    if(par[x] == x)return x;
    return par[x] = root(par[x]);
  }

  void unite(int x, int y){ //xとyの木を併合
    int rx = root(x); //xの根をrx
    int ry = root(y); //yの根をry
    if(rx == ry)return; //xとyの根が同じ
    par[rx] = ry; //xとyの根が同じでない時、xの根rxをyの根にryにつける。
  }

  bool same(int x, int y){//2つのデータx，yが属する木が同じならtrueを返す
    int rx = root(x);
    int ry = root(y);
    return rx == ry;
  }
};


int main(){
  int n, m;
  vector<bool> prime(8000000,false);

  for(int i = 2; i < sqrt(8000000); i++){
    int a = 1;
    while(i * a < 8000000){
      prime[a*i] = true;
      a++;
      }
  }

  while(cin >> n >> m, n and m){
    vector<bool> hatake(8000000, false);
    int cnt = 0;
    vector<int> v;

    for(int i = n;;i++){
      bool jud = false;

      if(cnt == m and !hatake[i]){
        cout << i << endl;
        break;
      }

      if(!hatake[i] and cnt < m){
        v.pb(i);
        int a = 1;
        while(i * a < 8000000){
          hatake[a*i] = true;
          a++;
        }
        cnt ++;
      }

    }
  }
  return 0;

}


Measured memory_bytes: 8784
#入力
n,x=map(int,input().split())
line=list(map(int,input().split()))
#累積和を計算しておく
#はじめに0を入れておくと、右からi番目で計算できる(i-1としなくて良い)
Sum=[0]
sum=0
#lineの後ろから値を取って、sumに足してlistに入れる
for i in range(n):
  sum+=line.pop()
  Sum.append(sum)
#大きい数で初期化(今回は小さい数の方が選ばれるので、十分大きい数で)
Ans=10**18
#それぞれのkについてコストを計算
for k in range(1,n):
  #pは純粋な移動のみのコスト
  p=0
  #kで割り切れる時は、n//k -1個のグループが出来る(最初は2kでグループを作る)
  #kで割り切れない時は、n//k 個のグループが出来る
  #よってn-1しておけばkで割り切れる時だけ-1出来る
  for i in range((n-1)//k):
    #はじめだけ処理が異なる
    if i==0:
      if n>=2*k:
        p+= (Sum[2*k])*5
      #2kの長さがなければ最初から最後まで足して終わり
      else:
        p+=(Sum[n])*5
        break
    else:
      if n> (k*i +2*k):
        #(i+1)*k+1から(i+2)*kまでの座標の和に移動コストをかける
        p+= (Sum[k*i +2*k]-Sum[k*(i-1) +2*k])*(2*i +5)
      else:
        p+= (Sum[n]-Sum[k*(i-1) +2*k])*(2*i +5)
        break
  #n*xが1)のコスト、k*xが2)のコスト
  ans=(n+k)*x + p
  #小さい方をAnsに代入
  Ans=min(Ans,ans)
#答え
print(Ans)

Measured memory_bytes: 99664
#pragma GCC optimize(2)
#include<bits/stdc++.h>
#define ll long long
#define maxn 2000005
#define inf 1e9
#define pb push_back
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
using namespace std;

inline int read()
{
	int x=0,w=1; char c=getchar();
	while(c<'0'||c>'9') {if(c=='-') w=-1; c=getchar();}
	while(c<='9'&&c>='0') {x=(x<<1)+(x<<3)+c-'0'; c=getchar();}
	return w==1?x:-x;
}

bool is[maxn];
ll pri[maxn],cnt,a[505][505],n;

inline void pre()
{
	for(int i=2;i<=maxn-5;i++)
	{
		if(!is[i]) pri[++cnt]=i;
		for(int j=1;j<=cnt&&pri[j]*i<=(maxn-5);j++)
		{
			is[i*pri[j]]=1;
			if(i%pri[j]==0) break;
		}
	}
}

inline ll X(int x){return pri[x];}
inline ll Y(int x){return pri[501+x];}
inline ll lcm(ll a,ll b){return a/__gcd(a,b)*b;}

int main()
{
	n=read(); pre();
	if(n==2)
	{
		printf("4 7\n23 10\n");
		return 0;
	}
	rep(i,0,n+1) rep(j,0,n+1) a[i][j]=1;
	rep(i,1,n) rep(j,1,n) if((i+j)%2==0)
	{
		a[i][j]=X((i+j)/2)*Y((i-j)/2);
	}
	rep(i,1,n) rep(j,1,n) if((i+j)%2==1)
	{
		ll p1=lcm(a[i-1][j],a[i][j-1]);
		ll p2=lcm(a[i+1][j],a[i][j+1]); a[i][j]=lcm(p1,p2)+1;
	}
	rep(i,1,n)
	{
		rep(j,1,n) printf("%lld ",a[i][j]);
		puts("");
	}
	return 0;
}

Measured memory_bytes: 8716
/**
 * code generated by JHelper
 * More info: https://github.com/AlexeyDmitriev/JHelper
 * @author
 */

#include <iostream>
#include <fstream>

#include <iostream>
#include "bits/stdc++.h"

using namespace std;

typedef unsigned long long ll;
typedef int                     integer;
#define int                     long long
#define ii                      pair<int,int>
#define vii                     vector<pair<int,int>>
#define vi                      vector<int>
#define vvi                     vector<vector<int>>
#define f(a,b,c)                for(int a=b;a<c;a++)
#define s(x)                    in>>x
#define s2(x,y)                 in>>x>>y
#define s3(x,y,z)               in>>x>>y>>z
#define s4(x,y,z,w)             in>>x>>y>>z>>w
#define p(x)                    out<<x<<endl
#define p2(x,y)                 out<<x<<" "<<y<<endl
#define pl(x)                   out<<x
#define p2l(x,y)                out<<x<<" "<<y
#define range(v)                v.begin(),v.end()
#define rst(x)                  memset(x, -1, sizeof(x))
#define UNVISITED               -1
#define VISITED                 0
#define EXPLORED                2

const int INF = 1e18L + 5;

void ssolve(std::istream& in, std::ostream& out){
    int N, W;
    s2(N, W);

    vi ws(N), vls(N);
    int total_value = 0;
    f(i, 0, N){
        s2(ws[i], vls[i]);
        total_value += vls[i];
    }

    vi dp(total_value + 1, INF);
    vi newdp(total_value + 1, INF);
    dp[0] = 0;
    newdp = dp;
    f(i, 0, N){
        for(int j = 0; j < total_value - vls[i] + 1; j++){
            newdp[j + vls[i]] = min(dp[j + vls[i]], dp[j] + ws[i]);
        }
        dp = newdp;
    }

    int ans = INF;
    for(int i = total_value; i >= 0; i--){
        if(dp[i] <= W){
            ans = i;
            break;
        }
    }
    p(ans);
    return;
}

class EKnapsack2 {
public:
void solve(std::istream& in, std::ostream& out) {
    ios_base::sync_with_stdio(false);
    in.tie(0);out.tie(0);
    int t;
    int READ = 0;
    if(READ) s(t);
    else t = 1;
    while(t--){
        ssolve(in, out);
    }
}
};

integer main() {
    EKnapsack2 solver;
    std::istream& in(std::cin);
     std::ostream& out(std::cout);
     solver.solve(in, out);
}

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

int main(){
cin.tie(0);
ios::sync_with_stdio(false);
int N;
vector<int> v;
int tmp;
cin>>N;
for(int i=0;i<N;i++){
    cin>>tmp;
    v.push_back(tmp);
}

sort(v.begin(),v.end());
double res=v[0];
for(int i=1;i<N;i++){
    res=(res+v[i])/2;
}
cout<<res<<endl;
//system("pause");
return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;

int n, b, mincount = 0, allmin = 0;
ll v[50], num = 0, ave = 0;
double a;
const double eps = 1e-6;

ll ncr(int n, int r) {
	ll res = 1, j = 1;
	for (int i = 0; i < r; i++) {
		if (j <= r && res%j == 0)res /= j++;
		res *= n--;
	}

	for (int i = j; i <= r; i++) {
		res /= i;
	}

	return res;
}

int main() {

	cin >> n >> a >> b;
	for (int i = 0; i < n; i++) {
		cin >> v[i];
	}
	sort(v, v + n);

	for (int i = 0; i < a; i++) {
		ave += v[n - i - 1];
		if (v[n-(int)a] == v[n - i - 1]) {
			mincount++;
		}
	}

	for (int i = 0; i < n; i++) {
		if (v[n-(int)a] == v[i])allmin++;
	}

	num = ncr(allmin, min(mincount, allmin - mincount));
	mincount++;
	for (int i = 1; i <= b-a; i++) {
		
		if (v[n-1] == v[n-(int)a] && v[n-(int)a-i] == v[n-(int)a]) {
			//cout << i + 1 << ":" << ncr(allmin, min(mincount, allmin - mincount)) << endl;
			num += ncr(allmin, min(mincount, allmin-mincount));
			mincount++;
		}
	}

	cout.precision(20);
	cout << ave/a << endl;
	cout << num << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
#define ll long long 
#define llinf 1e17
#define nllinf -4e18
 
#define vll vector<ll>
#define sll set<ll>
#define pll pair<ll,ll> 
#define vpll vector<pair<ll,ll > >
 
#define repup(a,b,i) for(i=a;i<=b;i++)
#define repdown(a,b,i) for(i=b; i>=a; i--)
#define repupx(a,b,i,x) for(i=a;i<=b;i+=x)
	
#define repit(v,it) for(it=v.begin(); it!=v.end(); it++)
#define itall(v) v.begin(),v.end()
#define pb push_back
#define pf push_front
#define mp make_pair
#define fr first
#define sc second
 
#define err(n) cout<<n<<" ";
#define t1 cout<<",";
 
ll MOD= 1e9 +7;
double p[305][305][305];
double ev[305][305][305];

int main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
//ll i,j,k;
ll f;
ll n;cin>>n;
ll cnt[4]={0};
repup(1,n,f){
	ll x;
	cin>>x;
	cnt[x]++;
}

p[cnt[1]][cnt[2]][cnt[3]]=1;

for(ll k= n; k>=0; k--){
	for(ll j= n; j>=0; j--){
		for (ll i=n; i>=0; i--){
			if(i==0&&j==0&&k==0)continue;
			if(i+j+k> n)continue;
			double p_waste= (double)(n-(i+j+k))/(double)n;
			ev[i][j][k]+= ((p_waste/(1-p_waste) )+1) *p[i][j][k]; 
			
			if(i!=0){   //
				p[i-1][j][k] += p[i][j][k]*(i)/(i+j+k);
				ev[i-1][j][k]+= ev[i][j][k]* i/ (i+j+k);}
			
			if(j!=0){
				p[i+1][j-1][k] += p[i][j][k]*(j)/(i+j+k);
				ev[i+1][j-1][k]+= ev[i][j][k]* j/(i+j+k) ;}
				
			
			if(k!=0){
				p[i][j+1][k-1]+=p[i][j][k]* (k)/(i+j+k);
				ev[i][j+1][k-1]+= ev[i][j][k]* k/(i+j+k);}
		}
	}
}
cout<<setprecision(10);
cout<<ev[0][0][0];
}

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

int main(){
	ll n;
	cin>>n;
	ll count=0,temp=1,ans=0;
	while(n%2==0){
		n/=2;
		count++;
	}
	while(count>0){
		ans++;
		count-=temp;
		temp++;
	}
	if(count<0)ans--;
	for(int i=3;i<sqrt(n);i++){
		count=0,temp=1;
		while(n%i==0){
			n/=i;
			count++;
		}
		while(count>0){
			ans++;
			count-=temp;
			temp++;
		}
		if(count<0)ans--;
	}
	if(n>2)ans++;
	cout<<ans<<endl;
	return 0;
}


Measured memory_bytes: 3644
n, m, k = map(int, input().split())

A = list(map(int, input().split()))
B = list(map(int, input().split()))

a, b=[0],[0]
for i in range(n):
    a.append(a[i]+A[i])
for i in range(m):
    b.append(b[i]+B[i])

ans, j=0,m

for i in range(n+1):
    if a[i]>k:
        break
    while b[j]>k-a[i]:
        j-=1
    ans=max(ans, i+j)
print(ans)

Measured memory_bytes: 47468
#include <bits/stdc++.h>
using namespace std;
//#include <ext/pb_ds/assoc_container.hpp>
//using namespace __gnu_pbds;
//typedef tree <int,null_type,less <int>, rb_tree_tag, tree_order_statistics_node_update> indexed_set;
// #include <ext/rope>
// using namespace __gnu_cxx;
typedef long long int ll;
typedef long double ld;
#define FAST                 \
    ios::sync_with_stdio(0); \
    cin.tie(0);              \
    cout.tie(0);
#define rep(g, i, n) for (ll g = i; g < n; g++)
#define rev(g, n, i) for (ll g = n - 1; g >= i; g--)
#define all(v) v.begin(), v.end()
#define pb push_back
#define mxe(v) *max_element(v.begin(), v.end())
#define mne(v) *min_element(v.begin(), v.end())
#define ve vector
#define lb lower_bound
#define ub upper_bound
#define bb break
#define cc continue
#define rem 1000000007
#define PI 3.141592653589793238462643383279502
ll power(ll x, ll y, ll p)
{
    ll res = 1; // Initialize result
    x = x % p;  // Update x if it is more than or
    while (y > 0)
    {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1; // y = y/2
        x = (x * x) % p;
    }
    return res;
}
ll modInverse(ll n, ll p)
{
    return power(n, p - 2, p);
}
struct point
{
    ll x, y;
};
const int MAXN = 500000;
int n, t[4 * MAXN];

//a is the array, v=1(root) tl=0, tr = n-1
void build(ve<int> &a, int v, int tl, int tr)
{
    if (tl == tr)
    {
        t[v] = a[tl];
    }
    else
    {
        int tm = (tl + tr) / 2;
        build(a, v * 2, tl, tm);
        build(a, v * 2 + 1, tm + 1, tr);
        t[v] = max(t[v * 2], t[v * 2 + 1]);
    }
}

//sum query, v=1, tl=0, tr=n-1, gives sum from l to r AND INDEXING OF ARRAY IS DONE FROM 0 (ZERO)
int mxx(int v, int tl, int tr, int l, int r)
{
    if (l > r)
        return 0;
    if (l == tl && r == tr)
    {
        return t[v];
    }
    int tm = (tl + tr) / 2;
    return max(mxx(v * 2, tl, tm, l, min(r, tm)), mxx(v * 2 + 1, tm + 1, tr, max(l, tm + 1), r));
}

//updating an element , v=1, tl=0,tr=n-1,pos=index (FROM 0) whose value has to be changed to new_val
// basically segment tree is being reconstructed but only at those nodes which will get affected
void update(int v, int tl, int tr, int pos, int new_val)
{
    if (tl == tr)
    {
        t[v] = new_val;
    }
    else
    {
        int tm = (tl + tr) / 2;
        if (pos <= tm)
            update(v * 2, tl, tm, pos, new_val);
        else
            update(v * 2 + 1, tm + 1, tr, pos, new_val);
        t[v] = max(t[v * 2], t[v * 2 + 1]);
    }
}
int main()
{
    int n, k;
    cin >> n >> k;
    vector<int> arr(n);
    rep(i, 0, n)
    {
        cin >> arr[i];
    }
    ve<int> fre(300001, 0);
    build(fre, 1, 0, 300000);
    ve <int> dp(300001,0);
    int ans=0;
    rep (i,0,n)
    {
        int L=max(0,arr[i]-k);
        int R=min(300000,arr[i]+k);
        int mx=mxx(1,0,300000,L,R);
        dp[arr[i]]=max(dp[arr[i]],mx+1);
        update(1,0,300000,arr[i],dp[arr[i]]);
        ans=max(ans,dp[arr[i]]);
    }
    cout<<ans<<"\n";

}

Measured memory_bytes: 10916
#include<iostream>
#include<vector>
#include<string>
#include <queue>
#include<map>
#include<set>
#include <cstring>
using namespace std;
#define ll long long int

#define mod 1000000007
int main()
{
   ll n ;
   cin>>n ;
   vector<ll> a(n) , pre(n , 0 );
   ll ans = 0 ;
   for(ll i = 0 ; i < n ; i++)
    cin>>a[i] ;

   pre[0] = a[0] ;
   for(ll i = 1 ; i < n ; i++)
   {
       pre[i] = pre[i - 1] + a[i];
   }

   for(ll i = 0 ; i < n - 1  ;i++)
   {
       ans += (((pre[n - 1] - pre[i])%mod)*a[i])%mod  ;
       ans = (ans + mod)%mod ;
   }

   ans = (ans + mod)%mod ;
   cout<<ans ;


}


Measured memory_bytes: 6428
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <sstream>
#include <string>

using namespace std;

void solve(int x1, int y1, int x2, int y2) {
  vector<int> rot = {0, -1, 1, 0};
  vector<int> v1 = {x2 - x1, y2 - y1};
  vector<int> v2 = {rot[0] * v1[0] + rot[1] * v1[1],
                    rot[2] * v1[0] + rot[3] * v1[1]};
  vector<int> p3 = {x2 + v2[0], y2 + v2[1]};
  vector<int> v3 = {rot[0] * v2[0] + rot[1] * v2[1],
                    rot[2] * v2[0] + rot[3] * v2[1]};
  vector<int> p4 = {p3[0] + v3[0], p3[1] + v3[1]};

  printf("%d %d %d %d\n", p3[0], p3[1], p4[0], p4[1]);
}

int main() {
  int x1, y1, x2, y2;
  cin >> x1 >> y1 >> x2 >> y2;
  solve(x1, y1, x2, y2);
  return 0;
}

Measured memory_bytes: 256
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {

    static BufferedReader in;
    static PrintWriter out;
    static StringTokenizer tok;
    static int MOD = 1000000007;

    void solve() throws IOException {

    	int x = ni();
    	int y = ni();

    	boolean a = true;
    	boolean b = true;

    	if(x < 0) a = false;
    	if(y < 0) b = false;

    	int xa = Math.abs(x);
    	int ya = Math.abs(y);

    	long ans = 0;

    	if(xa > ya){
    		ans = xa - ya;
    		if(a == true && b == true) ans += 2;
    		else if(a != b) ans++;
    		if(ya == 0) ans--;
    	}else if(xa < ya){
    		ans = ya - xa;
			if(a == false && b == false) ans += 2;
    		else if(a != b) ans++;
			if(ya == 0) ans--;
		}else if(xa == ya){
    		if(a != b) ans++;
		}

    	out.println(ans);

    }

    String ns() throws IOException {
        while (!tok.hasMoreTokens()) {
            tok = new StringTokenizer(in.readLine(), " ");
        }
        return tok.nextToken();
    }

    int ni() throws IOException {
        return Integer.parseInt(ns());
    }

    long nl() throws IOException {
        return Long.parseLong(ns());
    }

    double nd() throws IOException {
        return Double.parseDouble(ns());
    }

    String[] nsa(int n) throws IOException {
        String[] res = new String[n];
        for (int i = 0; i < n; i++) {
            res[i] = ns();
        }
        return res;
    }

    int[] nia(int n) throws IOException {
        int[] res = new int[n];
        for (int i = 0; i < n; i++) {
            res[i] = ni();
        }
        return res;
    }

    long[] nla(int n) throws IOException {
        long[] res = new long[n];
        for (int i = 0; i < n; i++) {
            res[i] = nl();
        }
        return res;
    }

    int k(int n) throws IOException {
        if(n == 0) return 1;
        else return n * k(n-1);
    }

    long s(int a, int n) throws IOException {
        return (a+n) * (n-a+1) / 2;
    }

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        tok = new StringTokenizer("");
        Main main = new Main();
        main.solve();
        out.close();
    }
}

Measured memory_bytes: 8276
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
int main() {
  int n,a[110],b[110]={0};
  cin >> n;
  for(int i=1; i<=n; i++) {
    cin >> a[i];
    a[i]+=a[i-1];
  }
  for(int i=1; i<=n; i++) {
    int c;
    cin >> c;
    b[i]=max(b[i-1],a[i])+c;
  }
  cout << b[n] << endl;
}

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

int main()
{
  int n, h, w;
  cin >> n >> h >> w;

  int ans = 0;
  for(int i = 0; i < n; i++){
    int a, b;
    cin >> a >> b;
    if(a >= h and b >= w) ans++;
  }

  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 256
N = int(input())
p = list(map(int, input().split()))

psort = sorted(p)
a = 0

for i in range(N):
    dist = psort[i] - p[i]
    if dist != 0:
        a += 1

if a == 0 or a == 2:
    print('YES')
else:
    print('NO')

Measured memory_bytes: 3060
#include<iostream>
#include<algorithm>
using namespace std;
int D=365;
int K=26;
int main()
{
  int d,cc=0,m=0,i,j,res=0;
  int c[K],s[D][K],t[D],l[K];
  cin >> d;
  for(i=0;i<K;i++){
    cin >> c[i];
    cc+=c[i];
  }
  for(i=0;i<d;i++)
    for(j=0;j<K;j++)
      cin >> s[i][j];
  for(i=0;i<d;i++){
    cin >> t[i];
    t[i]--;
  }
  fill(l,l+K,-1);
  for(i=0;i<d;i++){
    m+=cc;
    m-=c[t[i]]*(i-l[t[i]]);
    l[t[i]]=i;
    res+=s[i][t[i]]-m;
    cout << res << endl;
  }
  return 0;
}

Measured memory_bytes: 3604
#include <bits/stdc++.h>
using namespace std;
int PREP = (cin.tie(nullptr), ios::sync_with_stdio(false), cout << fixed << setprecision(9), 0);
//int SEGV = getenv("D") || (exit(system("D= SEGFAULT_SIGNALS=all catchsegv ./prog.exe") >> 8), 0);
int main() {
    int N; cin >> N;
    if (N % 1000 == 0) {
        cout << 0 << endl;
    } else {
        cout << (1000 - N % 1000) << endl;
    }
    return 0;
}

Measured memory_bytes: 3640
#include<stdio.h>

int main(void)
{
    int d,n;
    int i;
    int a=1;
    scanf("%d%d",&d,&n);
    
    for(i=0;i<d;i++)
        a=a*100;
    if(n==100)
        printf("%d",a*101);
    else
        printf("%d",a*n);
    return 0;
}


Measured memory_bytes: 128
import itertools

N,M,Q = list(map(int, input().split()))
inputs = [list(map(int, input().split())) for i in range(Q)]
items = [1] * N

finish = [M] * N

# (a,b,c,d)
def calc(A, tup):
    a,b,c,d = tup
    if A[b-1] - A[a-1] == c:
        return d
    else:
        return 0

RES = 0
    
seq = [i for i in range(1, M+1)]

all_col = itertools.combinations_with_replacement(seq, N)

for col in all_col:
    tmp = col[0]
    flg = True
    for c in col:
        if c < tmp:
            flg = False
            break
    if flg == False:
        continue
    res = 0
    for inp in inputs:
        res += calc(col, inp) 
    RES = max(RES, res)


print(RES)

Measured memory_bytes: 9164
#include <stdio.h>
#include <cstdio>
#include <iostream>
#include <queue>
#include <set>

using namespace std;

int main(){
  
  int A, B, C;
  scanf("%d%d%d", &A, &B, &C);
  
  if(A - B > C){
    std::cout << 0 << std::endl;
  }
  else std::cout << C - (A-B) << std::endl;
  
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
 
int main() {
	int n, alice=0, bob=0;
	cin >> n;
	vector<int> a(n);

	for(int i=0;i<n;i++) cin >> a.at(i);
	sort(a.begin(), a.end(), greater<int>());
	
	for(int i=0;i<n;i++){
		if(i%2==0) alice += a.at(i);
		else bob += a.at(i);
	}
	cout << alice - bob << endl;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define maxn 2010
using namespace std;
bitset<maxn> g[2][maxn], mp[maxn], now, pre, suf;
int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= i - 1; j++)
		{
			char c = getchar();
			while (c != '0' && c != '1') c = getchar();
			mp[i][j] = c - '0';
			mp[j][i] = 1 - mp[i][j];
		}
	for (int i = 1; i <= n - 1; i++)
		g[0][i][i + 1] = g[1][i + 1][i] = 1;
	for (int len = 3; len <= n; len++)
		for (int i = 1; i <= n - len + 1; i++)
		{
			int j = i + len - 1;
			now = g[0][i] & g[1][j] & (mp[i] | mp[j]);
			if (now.count()) g[0][i][j] = g[1][j][i] = 1;
		}
	pre[1] = 1;
	for (int i = 2; i <= n; i++)
		for (int j = 1; j <= i - 1; j++)
			if (pre[j] & g[0][j][i] & mp[i][j]) pre[i] = 1;
	suf[n] = 1;
	for (int i = n - 1; i >= 1; i--)
		for (int j = i + 1; j <= n; j++)
			if (suf[j] & g[0][i][j] & mp[i][j]) suf[i] = 1;
	int res = 0;
	for (int i = 1; i <= n; i++)
		if (pre[i] & suf[i]) res++;
	printf("%d\n", res);
	return 0;
}

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

typedef long long ll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<double> vd;
typedef vector<ll> vl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef pair<int,int> pii;
typedef pair<double, double> pdd;
typedef pair<ll, ll> pll;
typedef vector<pii> vii;
typedef vector<pll> vll;
typedef vector<pdd> vdd;

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define mem(a,b) memset(a, b, sizeof(a) )
#define all(x) (x).begin(),(x).end()
#define INF 1e18
#define MOD 1000000007
#define PB push_back
#define MP make_pair
#define F first
#define S second

inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }

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

int dp[80][80][12810];

int main(){
    int h,w;
    cin>>h>>w;
    vvi a(h,vi(w)),b(h,vi(w)),c(h,vi(w));
    rep(i,h)rep(j,w)cin>>a[i][j];
    rep(i,h)rep(j,w)cin>>b[i][j];
    rep(i,h)rep(j,w)c[i][j]=abs(a[i][j]-b[i][j]);
    mem(dp,0);
    dp[0][0][c[0][0]]=1;
    rep(i,h){
        rep(j,w){
            for(int k=0;k<=12800;++k){
                if(dp[i][j][k]==1){
                    if(i+1<h){
                        dp[i+1][j][k+c[i+1][j]]=1;
                        dp[i+1][j][abs(k-c[i+1][j])]=1;
                    }
                    if(j+1<w){
                        dp[i][j+1][k+c[i][j+1]]=1;
                        dp[i][j+1][abs(k-c[i][j+1])]=1;
                    }
                }
            }
        }
    }
    for(int i=0;i<=12800;++i){
        if(dp[h-1][w-1][i]==1){
            cout<<i<<endl;
            return 0;
        }
    }
}

Measured memory_bytes: 323888
# Aizu Problem 00150: Twin Prime
#
import sys, math, os, bisect

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def primes2(n):
    """ Input n>=6, Returns a list of primes, 2 <= p < n """
    n, correction = n-n%6+6, 2-(n%6>1)
    sieve = [True] * (n//3)
    for i in range(1,int(n**0.5)//3+1):
      if sieve[i]:
        k=3*i+1|1
        sieve[      k*k//3      ::2*k] = [False] * ((n//6-k*k//6-1)//k+1)
        sieve[k*(k-2*(i&1)+4)//3::2*k] = [False] * ((n//6-k*(k-2*(i&1)+4)//6-1)//k+1)
    return [2,3] + [3*i+1|1 for i in range(1,n//3-correction) if sieve[i]]

primes = primes2(10050)

while True:
    n = int(input())
    if n == 0:
        break
    idx = bisect.bisect_left(primes, n)
    while True:
        #if idx == len(primes):
        #    idx -= 1
        if primes[idx] > n:
            idx -= 1
        if primes[idx] - primes[idx - 1] == 2:
            print(primes[idx - 1], primes[idx])
            break
        idx -= 1

Measured memory_bytes: 7944
#pragma GCC optimize("O3")
#include <bits/stdc++.h>

using namespace std;

typedef int64_t  ll;
typedef uint64_t ull;

#define rep(i,n)   for (int i = 0; i < (n); i++)
#define rrep(i,n)  for (int i = (n)-1; i >= 0; i--)
#define rep1(i,n)  for (int i = 1; i <= (n); i++)
#define rrep1(i,n) for (int i = (n); i > 0; i--)

int main(void) {
    string s;
    cin >> s;
    if (s=="Sunny") cout << "Cloudy" << endl;
    if (s=="Cloudy") cout << "Rainy" << endl;
    if (s=="Rainy") cout << "Sunny" << endl;
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long
#define pb push_back
#define endl '\n'
#define mod 1000000007
#define mod1 1000000009
#define line cout<<"----------------------"<<endl
#define mp make_pair
#define fast ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define filein freopen("input.txt","r",stdin)
#define fileout freopen("output.txt","w",stdout)
using namespace std;
const ll   mx=100009;
int  main()
{
    int a,b;
    cin>>a>>b;
    ll ans=a*(a-1)/2+b*(b-1)/2;
    cout<<ans<<endl;
}


Measured memory_bytes: 256
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inp(): return int(input())
def inpl(): return list(map(int, input().split()))
def inpl_s(): return list(input().split())
atoz = [chr(i) for i in range(97,97+26)]

N,C = inpl()
Cost = [inpl() for i in range(C)]
Colors = [inpl() for i in range(N)]

nums_0 = [0]*(C+1)
nums_1 = [0]*(C+1)
nums_2 = [0]*(C+1)

for y in range(N):
	for x in range(N):
		if (x+y)%3 == 0:
			nums_0[Colors[y][x]] += 1
		elif (x+y)%3 == 1:
			nums_1[Colors[y][x]] += 1
		elif (x+y)%3 == 2:
			nums_2[Colors[y][x]] += 1

ans = INF
for c0 in range(1,C+1):
	for c1 in range(1,C+1):
		if c1 == c0: continue
		for c2 in range(1,C+1):
			if c2 == c1 or c2 == c0: continue
			tmp = 0
			for i in range(1,C+1):
				tmp += Cost[i-1][c0-1]*nums_0[i]
				tmp += Cost[i-1][c1-1]*nums_1[i]
				tmp += Cost[i-1][c2-1]*nums_2[i]
			ans = min(ans,tmp)

print(ans)


Measured memory_bytes: 6764
void main() {
  problem();
}

void problem() {
  auto A = scan!long;
  auto B = scan!long;
  auto C = scan!long;
  auto K = scan!int;

  bool solve() {
    foreach(p; [0,1,2].permutationsWithRepetitions(K)) {
      auto a = A;
      auto b = B;
      auto c = C;
      foreach(_; 0..p.count(0)) a *= 2;
      foreach(_; 0..p.count(1)) b *= 2;
      foreach(_; 0..p.count(2)) c *= 2;
      [a,b,c].deb;

      if (a < b && b < c) return true;
    }

    return false;
  }

  writeln(solve() ? "Yes" : "No");
}

// ----------------------------------------------

import std.stdio, std.conv, std.array, std.string, std.algorithm, std.container, std.range, core.stdc.stdlib, std.math, std.typecons, std.numeric;
T[][] combinations(T)(T[] s, in int m) {   if (!m) return [[]];   if (s.empty) return [];   return s[1 .. $].combinations(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].combinations(m); }
string scan(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }
T scan(T)(){ return scan.to!T; }
T[] scan(T)(int n){ return n.iota.map!(i => scan!T()).array; }
void deb(T ...)(T t){ debug writeln(t); }
alias Point = Tuple!(long, "x", long, "y");

import std.concurrency;
Generator!(T[]) permutationsWithRepetitions(T)(T[] data, in uint n)
in {
    assert(!data.empty && n > 0);
} body {
    return new typeof(return)({
        if (n == 1) {
            foreach (el; data)
                yield([el]);
        } else {
            foreach (el; data)
                foreach (perm; permutationsWithRepetitions(data, n - 1))
                    yield(el ~ perm);
        }
    });
}

// -----------------------------------------------


Measured memory_bytes: 3864
use proconio::{
    fastout, input,
    marker::{Bytes, Chars, Isize1, Usize1},
};

fn main() {
    input! {
        x:usize
    }
    println!(
        "{}",
        if x < 600 {
            8
        } else if x < 800 {
            7
        } else if x < 1000 {
            6
        } else if x < 1200 {
            5
        } else if x < 1400 {
            4
        } else if x < 1600 {
            3
        } else if x < 1800 {
            2
        } else if x < 2000 {
            1
        } else {
            0
        }
    );
}


Measured memory_bytes: 2144
#include <cassert>

#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>

// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <boost/foreach.hpp>
//#include <boost/range/algorithm.hpp>
#define rep(i,j,k) for(int i=(int)j;i<(int)k;i++)
#define ll long long
#define Sort(v) sort(all(v))
#define INF 1000000000
#define END return 0
#define pb push_back
#define se second
#define fi first
#define pb push_back
#define all(v) (v).begin() , (v).end()
#define MP make_pair
#define MOD 1000000007LL;
using namespace std;
int day[12]={31,28,31,30,31,30,31,31,30,31,30,31};

int main (){ 
    int n;cin>>n;
    vector<ll> a(n),b(n),c(n);
    ll ans=0;
    rep(i,0,n){
        cin>>a[i]>>b[i];
        
    }

    for(int i=n-1;i>=0;i--){
        if(((a[i]+ans)%b[i])!=0)ans+=b[i]-((a[i]+ans)%b[i]);
    }
    cout<<ans<<endl;

    return 0;
}


/*
3 5 3

*/


Measured memory_bytes: 2560
#include <iostream>
#include <algorithm>
#include <cmath>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define REP(i,k,n) for(int i = k; i < (int)(n); i++)
using namespace std;

char s[50+10][50+10];
int main(){
        int H,W;
        cin >> H >> W;
        rep(i,W+2) rep(j,W+2) s[i][0]='.';
        rep(i,W+2) rep(j,W+2) s[i][W+2]='.';
        rep(i,W+2) rep(j,W+2) s[0][j]='.';
        rep(i,W+2) rep(j,W+2) s[H+2][j]='.';
        rep(i,H) rep(j,W) cin>>s[i+1][j+1];
        REP(i,1,H+1) REP(j,1,W+1){
                if(s[i][j] == '#') {
                        bool Flag = false;
                        if(s[i-1][j] == '#') Flag = true;
                        if(s[i+1][j] == '#') Flag = true;
                        if(s[i][j-1] == '#') Flag = true;
                        if(s[i][j+1] == '#') Flag = true;

                        if(Flag == false) {
                                cout << "No" << endl;
                                return 0;
                        }
                }
        }
        cout << "Yes" << endl;
        return 0;
}


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

int main(){
  int N;
  cin >> N;
  int flag = 0;
  for(int i = 0; i < N; i++){
    string S;
    cin >> S;
    if (S == "Y"){
      flag = 1;
      cout << "Four" << endl;
      break;
    }
  }
  if (flag == 0){
    cout << "Three" << endl;
  }
}

Measured memory_bytes: 256
#include <iostream>

using namespace std;

int main() {
    char s[100005]={};
    int n,k=0;
    cin>>n;
    cin>>s;
    for(int i=1;i<n;i++){
        if(s[i]!=s[i-1]){
            k++;
            s[k]=s[i];
        }
    }
    k++;
    s[k]='\0';
    cout<<k;
    
    return 0;
}

Measured memory_bytes: 384
class UnionFind():
    '''
    @properties
        parents:
            - 各要素の親要素の番号を格納するリスト
            - 要素が根の場合はそのグループの要素数を格納する
    '''
    def __init__(self,n):
        self.n = n 
        self.parents = [-1] * n

    def __str__(self):
        return '\n'.join('{}: {}'.format(r,self.members(r)) for r in self.roots())
    
    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 members(self,x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i,x in enumerate(self.parents) if x < 0 ]
    
    def weighted_roots_sizes(self):
        return [ self.size(i) for i,x in enumerate(self.parents) if x < -1 ]
    
    def size(self,x):
        return -self.parents[self.find(x)]

N,M = map(int,input().split(' '))
bridges = [ list(map(int,input().split(' '))) for _ in range(M) ]
uf = UnionFind(N)
base_num = N * (N-1) //2
output_list = [0]*(M+1)
output_list[M] = base_num

for i in reversed(range(M)):
    bridge_from = bridges[i][0] - 1
    bridge_to = bridges[i][1] - 1
    current_amount = 0
    if uf.find(bridge_from) == uf.find(bridge_to):
        output_list[i] = output_list[i+1]
        continue
    output_list[i] = output_list[i+1] - uf.size(bridge_from) * uf.size(bridge_to)
    uf.union(bridge_from,bridge_to)

for i in range(1,M+1):
    print(output_list[i])


Measured memory_bytes: 35968
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define loop(i,a,b) for (int i=a; i<b; ++i)
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    vector <ll> X(9);
    loop(i,0,9) cin >> X[i];
    ll N;
    cin >> N;
    loop(i,0,N)
    {
        ll x;
        cin >> x;
        loop(i,0,9) {
            if (x==X[i]) X[i]=0;
        }
    }
    vector < vector <ll> > combos = { {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0, 4,8}, {2,4,6}  };
    loop(i,0,combos.size())
    {
        if (X[combos[i][0]] + X[combos[i][1]] + X[combos[i][2]] == 0)
        {
            cout << "Yes\n"; return 0;
        }
    }
    cout << "No\n";
    return 0;
}

Measured memory_bytes: 256