akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <vector>
#include <cmath>

int main()
{
    long long N, D;
    std::cin >> N >> D;
    std::vector<long long> X(N);
    std::vector<long long> Y(N);
    for(int i=0; i<N; i++)
    {
        std::cin >> X[i] >> Y[i];
    }

    int ans = 0;
    long long dist = D*D;

    for(int i=0; i<N; i++)
    {
        long long p_dist = ( X[i] * X[i] ) + ( Y[i] * Y[i] );

        if(p_dist <= dist)
        {
            ans++;
        }        
    }

    std::cout << ans << std::endl;

    return 0;
}

Measured memory_bytes: 6424
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <random>
#include <cstdio>
#include <cstring>
#include <cmath>

// for i in f..<t { as swift
#define forin(i, f, t) for(auto i = f; i < t; i++)

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

int main() {
    int n;
    cin >> n;
    vector<ll> a(n);
    for(auto &v: a) cin >> v;
    sort(a.begin(), a.end());
    const auto max = a[n - 1];
    auto sub = a[0];
    auto sh = double(max) / 2;
    auto minDiff = abs(sh - sub);
    forin(i, 1, n - 1) {
        auto diff = abs(sh - a[i]);
        if (diff < minDiff) {
            sub = a[i];
            minDiff = diff;
        }
    }
    
    cout << max << ' ' << sub << endl;
}


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

// int/long:		-2147483648 - 2147483648 (-2^31 <= int < 2^31)
// long/long long:	-9223372036854775808 - 9223372036854775807 (-2^63 <= long < 2^63)
#define	INF (1<<29)
//536870912

#define	MOD 1000000007

int	main() {
	int A, B, C, D;
	cin >>A >>B >>C >>D;
	A=max(A, C);
	B=min(B, D);
	cout <<max(0, B-A) <<endl;
	return 0;
}



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

namespace ClassLibrary1
{
    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }


    public class Class1
    {
        static Dictionary<Tuple<long, long>, long> dic = new Dictionary<Tuple<long, long>, long>();

        static long mod = 1000000007;

        static void Main(string[] args)
        {

            var AA = ReadLongArr();
            var N = AA[0];
            var M = AA[1];

            var rest = new bool[N];
            var pe = new int[N];
            for (int i=0; i<N; i++)
            {
                rest[i] = false;
                pe[i] = 0;
            }

            for(int i=0; i< M; i++)
            {
                var ll = ReadStringArr();
                var p = int.Parse(ll[0]);
                if (rest[p-1])
                {
                    continue;
                }

                if (ll[1] == "AC")
                { 
                    rest[p-1] = true;
                }
                else
                {
                    pe[p-1]++;
                }

            }

            var solved = 0;
            var peAll = 0;
            for(int i=0; i<N; i++)
            {
                if (rest[i])
                {
                    solved++;
                    peAll += pe[i];
                }
            }

            Console.WriteLine(solved + " " + peAll );


        }

        public static long Factorial(int n)
        {
            if (n == 0)
                return 1L;
            return n * Factorial(n - 1);
        }

        private static string ReadString()
        {
            return Console.ReadLine();
        }
        private static string[] ReadStringArr()
        {
            return Console.ReadLine().Split(' ');
        }
        private static long ReadLong()
        {
            return long.Parse(Console.ReadLine());
        }
        private static long[] ReadLongArr()
        {
            string[] s = ReadStringArr();
            long[] l = new long[s.Length];
            for(int i=0; i<l.Length; i++)
            {
                l[i] = long.Parse(s[i]);
            }

            return l;
        }
    }

}


Measured memory_bytes: 15584
#include <bits/stdc++.h>
//#include <boost/array.hpp>
//#include <boost/range/numeric.hpp>
//#include <boost/range/algorithm.hpp>
//#include <boost/multiprecision/cpp_int.hpp>

#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

using namespace std;
//using namespace boost::multiprecision;

constexpr long long INF = LLONG_MAX;
constexpr long long MOD = 1000000007;
constexpr long double PI = M_PI;

#define FOR(i,r,n) for(ll i = (ll)(r); i < (ll)(n); ++i)
#define RFOR(i,n,r) for(ll i = (ll)(n-1); i >= r; --i)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) RFOR(i,n,0)
#define ALL(x) x.begin(),x.end()
#define CALL(x) x.cbegin(),x.cend()
#define RALL(x) x.rbegin(),x.rend()
#define CRALL(x) x.crbegin(),x.crend()

#define cout cout << fixed << setprecision(12)
#define dbglf cerr << '\n'

#define ACCM(arr) accumulate(ALL(arr),0LL)
#define Yes(ex) cout << ((ex) ? "Yes" : "No") << endl
#define YES(ex) cout << ((ex) ? "YES" : "NO") << endl

using ll = long long int;
using ull = unsigned long long int;
using ld = long double;
using vi = vector<ll>;
using vvi = vector<vi>;
using vp = vector<pair<ll, ll>>;
using vs = vector<string>;
using vc = vector<char>;
using lst = list<ll>;
using pq = priority_queue<ll>;

template < typename T >
inline void veccin(vector<T>& v) {
    for (auto && e : v) { cin >> e; }
}

template < typename T >
inline void dbg(T a) { cerr << a << ' '; }

ll n, m, k;
ll ans = INF, sum = 0, cnt = 0;
//ld d;
bool flag = false;

/*--------------------template--------------------*/

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

    cin >> n >> m >>k;
	vi c(n);
	vvi a(n,vi(m));
	REP(i,n) {cin >> c[i];veccin(a[i]);}
	ull bit = 1<<n;
	REP(i,bit){
		bitset<12> bs = i;
    	vi test(m,0);
    	sum = 0;
    	//dbg(bs);
    	REP(j,n){
        	if(bs[j]){
              	REP(l,m)test[l]+=a[j][l];
        		sum+=c[j];
            	//dbg(c[j]);
            }
        }
    	REP(j,m){
        	if(test[j]<k){
            	goto nex;
            }
        }
    	ans = min(sum,ans);
      nex:;
    }
    cout << (ans==INF?-1:ans) << endl;
}


Measured memory_bytes: 3664
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll INF = 0xffffffffff;
const int N = 1e5 + 100;
int n, a[N];


int main() {
	cin>>n;
  for(int i=0;i<n;i++)scanf("%d", &a[i]);
  ll ans = INF;
  for(ll i=1;i<=100;i++) {
  	ll t = 0;
    for(int j=0;j<n;j++) {
    	t += (a[j] - i) * (a[j] - i);
    }
    ans = min(ans, t);
  }
  cout<<ans<<endl;
    return 0;
}


Measured memory_bytes: 256
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
long long sum[200005];
int main(){
	int i;
	int n;
	long long ans=0x7fffffffffffffff;
	
	scanf("%d", &n);
	for(i=1; i<=n; i++){
		scanf("%lld", &sum[i]);
		sum[i]+=sum[i-1];
	}
	for(i=1; i<n; i++){
		ans=min(ans, abs(sum[n]-2*sum[i]));
	}
	printf("%d", ans);
	return 0;
}

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

using namespace std;
typedef long long ll;
const int N = 1e6+100;
struct node{
    int id;
    ll len;
};
ll dis[N];
vector<pair<int,ll> > G[N];
bool operator<(node a,node b){
    return a.len>b.len;
}
bool vis[N];
priority_queue<node> q;
int n,m;
void dij(int s){
    for(int i=1;i<=n;i++) dis[i]=(1e18);
    memset(vis,0,sizeof(vis));
    dis[s]=0;
    q.push({s,0});
    while(!q.empty()){
        node rt=q.top();q.pop();
        int u=rt.id;
        if(vis[u]) continue;
        vis[u]=1;
        for(auto V:G[u]){
            int v=V.first;
            ll w=V.second;
            if(dis[v]>dis[u]+w){
                dis[v]=dis[u]+w;
            }
            q.push({v,dis[v]});
        }
    }
}
int main(){
    cin>>n>>m;
    ll u,v,w;
    for(int i=2;i<=n;i++) G[i].push_back({i-1,0});
    for(int i=1;i<=m;i++){
        cin>>u>>v>>w;
        G[u].push_back({v,w});
    }
    dij(1);
    if(dis[n]==(1e18)){
        cout<<-1<<endl;
    }else{
        cout<<dis[n]<<endl;
    }
    return 0;
}

Measured memory_bytes: 34424
#include<stdio.h>
#define MOD 1000000000000000000

int main()
{
  int N;
  scanf("%d",&N);
  long A[N],temp=1,temp2;
  int flag=0;
  for(int i=0;i<N;i++){
    scanf("%ld",&A[i]);
    if(A[i]==0){
      flag=1;
    }
  }
  
  if(flag==1){
    temp=0;
  }else{
    for(int i=0;i<N;i++){
      if(temp > MOD || (A[i]>MOD/temp)){
        temp=-1;
        break;
      }
      temp*=A[i];
    }
  }
  printf("%ld",temp);
}


Measured memory_bytes: 2472
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
from scipy.sparse.csgraph import dijkstra
from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    a,v = map(int,ipt().split())
    b,w = map(int,ipt().split())
    t = int(input())

    if w > v:
        print("NO")
    elif w == v:
        if a == b:
            print("YES")
        else:
            print("NO")
    else:
        if abs(a-b) <= t*(v-w):
            print("YES")
        else:
            print("NO")

    return

if __name__ == '__main__':
    main()


Measured memory_bytes: 37468
#include<iostream>
using namespace std;
int main()
{
	int a,b,c;	cin>>a>>b>>c;
	if(a==b&&a!=c)
		cout<<"Yes"<<endl;
	else if(b==c&&b!=a)
		cout<<"Yes"<<endl;
	else if(a==c&&a!=b)
		cout<<"Yes"<<endl;
	else
		cout<<"No"<<endl;
}

Measured memory_bytes: 256
use v6;

my ($a, $b) = get().chomp.split(' ');
$a = 14 if ($a == 1);
$b = 14 if ($b == 1);
if ($a == $b) {
	say "Draw";
} elsif ($a > $b) {
	say "Alice";
} else {
	say "Bob";
}

exit;

Measured memory_bytes: 67568
#include <iostream>
#include <cmath>

using namespace std;

int dp[103][103],arr[103][103];
char s[103][103];

int main () {
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>s[i][j];
			arr[i][j]=(s[i][j]=='#');
		}
	}
	for(int i=2;i<=n;i++){
		dp[i][1]=dp[i-1][1]+(arr[i][1]!=arr[i-1][1]);
	}
	for(int i=2;i<=m;i++){
		dp[1][i]=dp[1][i-1]+(arr[1][i]!=arr[1][i-1]);
	}
	for(int i=2;i<=n;i++){
		for(int j=2;j<=m;j++){
			dp[i][j]=min(dp[i-1][j]+(arr[i-1][j]!=arr[i][j]),dp[i][j-1]+(arr[i][j-1]!=arr[i][j]));
		}
	}
	cout<<dp[n][m]/2+(arr[1][1] || arr[n][m]);



return 0;
}



Measured memory_bytes: 384
// G++ MACRO.CPP -STD=C++14
#include <bits/stdc++.h>
typedef long long ll;
const int INF = 1e9;
const int MOD = 1e9+7;
const ll LINF = 1e18;
using namespace std;

#define dump(x)  cout << #x << " = " << (x) << endl;
#define YES(n) cout << ((n) ? "YES" : "NO"  ) << endl
#define Yes(n) cout << ((n) ? "Yes" : "No"  ) << endl
#define POSSIBLE(n) cout << ((n) ? "POSSIBLE" : "IMPOSSIBLE"  ) << endl
#define Possible(n) cout << ((n) ? "Possible" : "Impossible"  ) << endl
#define possible(n) cout << ((n) ? "possible" : "impossible"  ) << endl

#define SANKOU(n,a,b) cout << ((n) ? (#a) : (#b) ) << endl

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<(n);++i)
#define REPR(i,n) for(int i=n;i>=0;i--)

#define FOREACH(x,a) for(auto& (x) : (a) )

#define WFA(d,v) REP(k,v)REP(i,v)REP(j,v)d[i][j]=min(d[i][j],d[i][k]+d[k][j])

#define SCOUT(x) cout<<(x)<<" "
#define ENDL cout<<endl

#define VECCIN(x) for(auto&youso_: (x) )cin>>youso_
#define VECIN2(x,y) REP(i,x.size())cin>>x[i]>>y[i]
#define VECCOUT(x) if(1){for(auto tt=x.begin();tt!=x.end();tt++){if(tt!=x.begin())cout<<" ";cout<<(*tt);}cout<<endl;}

#define ALL(obj) (obj).begin(),(obj).end()

#define EXIST(n,x) (find(ALL(n),x)!=n.end())
#define UNIQUE(obj) sort(ALL( obj )); obj.erase(unique(ALL(obj)),obj.end())
#define EN(x) if(1){cout<<#x<<endl;return 0;}
#define COUT(x) cout<<(x)<<endl
void CINT(){}
template <class Head,class... Tail>
void CINT(Head&& head,Tail&&... tail){
    cin>>head;
    CINT(move(tail)...);
}
#define CIN(...) int __VA_ARGS__;CINT(__VA_ARGS__)
#define LCIN(...) ll __VA_ARGS__;CINT(__VA_ARGS__)
#define SCIN(...) string __VA_ARGS__;CINT(__VA_ARGS__)

template <class T = ll>
T IN(){T x;cin>>x;return (x);}

template <class Head>
void VT(Head head){}
template <class Head,class Seco,class... Tail>
void VT(Head&& head,Seco&& seco,Tail&&... tail){
    seco.resize(head);
    VT(head,move(tail)...);
}
void VT2(){}
template <class Head,class... Tail>
void VT2(Head&& head,Tail&&... tail){
  VECCIN(head);
  VT2(move(tail)...);
}

template <class Head>
void VT3(Head&& head){}
template <class Head,class Seco,class... Tail>
void VT3(Head&& head,Seco&& seco,Tail&&... tail){
  seco[head]=IN();
  VT3(head,move(tail)...);
}

#define VC1(n,...) V __VA_ARGS__;VT(n,__VA_ARGS__);VT2(__VA_ARGS__); //aaabbbccc
#define VC2(n,...) V __VA_ARGS__;VT(n,__VA_ARGS__);REP(i,n)VT3(i,__VA_ARGS__); //abcabcabc

// #include <boost/multiprecision/cpp_int.hpp>
// using namespace boost::multiprecision; // cpp_int

#define P pair<ll,ll>
#define V vector<ll>
#define M map<int,int>
#define S set<int>
#define PQ priority_queue<int>
#define PQG priority_queue<int,V,greater<int>>

#define str string

#define pb(a) push_back(a)
#define mp make_pair


int main(){
  CIN(n,m);VC2(m,a,b);
  vector<V> edge(n,V(n,0));
  REP(i,m){a[i]--;b[i]--;edge[a[i]][b[i]]=1;edge[b[i]][a[i]]=1;}
  V v(n-1);iota(ALL(v),1);
  int pat = 0;
  do{
    bool flag=true;
    if(!edge[0][v[0]])flag=false;
    REP(i,n-2)
      if(!edge[v[i]][v[i+1]])flag=false;
    if(flag)
      pat++;
  }while(next_permutation(ALL(v)));
  COUT(pat);
 
  return 0;
}


Measured memory_bytes: 256
require 'pp'
class Solve
  attr_reader :map

  EXPAND = (-3..3).map { |i| [[i, 0], [0, i]] }.flatten(1)

  def initialize(map)
    @map = map.dup
  end

  def bomb(x, y)
    @map[x][y] = 0

    EXPAND.each do |dx, dy|
      _x, _y = x + dx, y + dy

      next if (_x < 0 || _x >= 8) || (_y < 0 || _y >= 8)

      if @map[_x][_y] == 1
        bomb(_x, _y)

        @map[_x][_y] = 0
      end
    end
  end
end

n = gets.to_i
n.times do |i|
  gets

  map = []
  8.times do
    map.push(gets.chomp.split(//).map(&:to_i))
  end
  map = map.transpose

  x, y = gets.to_i - 1, gets.to_i - 1

  solve = Solve.new(map)
  solve.bomb(x, y)

  puts "Data #{i + 1}:"
  puts solve.map.transpose.map(&:join)
end

Measured memory_bytes: 9008
#include <iostream>
#include <vector>
#include <queue>
using namespace std;

typedef long long i64;

i64 a,b,c;

int rec(int A,int B,int C)
{
	if(A % 2 == 1 || B % 2 == 1 || C % 2 == 1)
		return 0;
	int p = A / 2;
	int q = B / 2;
	int r = C / 2;
	return rec(q + r , p + r , p + q) + 1;
}
int main()
{
	cin >> a >> b >> c;

	if(a % 2 == 0 && a == b && b == c)
	{
		cout << -1 << endl;
		return 0;
	}

	cout << rec(a,b,c) << endl;
	return 0;
}


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

int main(){
  int n;
  cin >> n;
  vector<int> point(n,0);
  for(int i=0;i<n*(n-1)/2;i++){
    int a,b,c,d;
    cin >> a >> b >> c >> d; a--; b--;
    if(c<d){
      point[b] += 3;
    }else if(c>d){
      point[a] += 3;
    }else{
      point[a]++; point[b]++;
    }
  }
  vector<int> rank = point;
  sort(rank.begin(),rank.end());
  
  for(int i=0;i<n;i++){
    int pos = upper_bound(rank.begin(),rank.end(),point[i]) - rank.begin();
    cout << n-pos+1 << endl;
  }
}

Measured memory_bytes: 1216
def d_replacing():
    from collections import Counter
    N = int(input())
    A = [int(i) for i in input().split()]
    Q = int(input())
    Queries = [[int(i) for i in input().split()] for j in range(Q)]

    total = sum(A)
    sequence = Counter(A)

    ans = []
    for b, c in Queries:
        total += (c - b) * sequence[b]  # 値を変更
        ans.append(total)
        sequence[c] += sequence[b]  # 要素の個数を更新
        del sequence[b]  # 「個数を 0 とする」でもよい
    return ' '.join(map(str, ans))

print(d_replacing())

Measured memory_bytes: 49172
using System;

namespace AtCoder.ABC._124
{
    class c
    {
        static void Main(string[] args)
        {
            var line = Console.ReadLine().Trim();
            var len = line.Length;
            var cntOdd = 0;
            var cntEve = 0;
            for(var i = 0; i < len; ++i)
            {
                if(i % 2 == 0)
                {
                    if(line[i] == '1')
                    {
                        ++cntEve;
                    }
                }
                else
                {
                    if (line[i] == '1')
                    {
                        ++cntOdd;
                    }
                }
            }
            Console.WriteLine(Math.Min(Math.Ceiling(len / 2.0d) - cntEve + cntOdd, cntEve + (len / 2 - cntOdd)));
        }
    }
}


Measured memory_bytes: 13268
n = gets.to_i
if n == 0
    puts 0
    exit
end
ans = []
i = 0
while n != 0
    if n%2 == 1
        ans[i] = 1
        n -= (i%2==0 ? 1 : -1)
    else
        ans[i] = 0
    end
    n /= 2
    i += 1
end
puts ans.reverse.join

Measured memory_bytes: 1788
n,m = map(int, input().split())
li = [list(map(int, input().split())) for i in range(n)]
li.sort(key=lambda x:x[0])
ans = 0

while True:
    if m == 0:
        print(ans)
        quit()
    if li[0][1] == 0:
        li.pop(0)
    ans += li[0][0]
    li[0][1] -= 1
    m -= 1


Measured memory_bytes: 29024
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(n);i++)
#define loop(i,x,n) for(int i=(x);i<(n);i++)
#define all(v) (v).begin(),(v).end()
#define int long long
using namespace std;
const int MOD=1e9+7;
const int INF=1e15;
template<typename T> void cmax(T &a, T b) {a = max(a, b);}
template<typename T> void cmin(T &a, T b) {a = min(a, b);}


signed main(){
  int n;
  cin>>n;
  string s;
  cin>>s;
  vector<int> w(n+1),e(n+1);
  rep(i,s.size()){
    if(s[i]=='W'){
      w[i+1]=1;
    }else{
      e[i+1]=1;
    }
  }
  rep(i,n){
    w[i+1]+=w[i];
    e[i+1]+=e[i];
  }

  int ans=INF;
  loop(i,1,n+1){
    int tmp=w[i-1]+e.back()-e[i];
    cmin(ans,tmp);
  }cout<<ans<<endl;
 return 0;
}


Measured memory_bytes: 5380
#include <bits/stdc++.h> 
using namespace std;
const int MAX_N=1e8;int a[MAX_N];
int main(){
    int m;cin>>m;
    int flag=1;
    while(m--){
    	int t,x,y;
    	cin>>t>>x>>y;
    	int p=x+y;
    	if(t<p||((t-p)%2!=0))
			flag=0;
	}if(flag) cout<<"Yes"<<endl;
	else cout<<"No"<<endl;
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <array>
#include <algorithm>
#include <vector>
#include <bitset>
#include <set>
#include <unordered_set>
#include <cmath>
#include <complex>
#include <deque>
#include <iterator>
#include <numeric>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <limits>
#include <iomanip>
#include <functional>
#include <cassert>
using namespace std;

using ll=long long;
template<class T> using V = vector<T>;
template<class T, class U> using P = pair<T, U>;
using vll = V<ll>;
using vvll = V<vll>;
#define rep(i, k, n) for (ll i=k; i<(ll)n; ++i)
#define REP(i, n) rep(i, 0, n)
#define ALL(v) v.begin(),v.end()
template < class T > inline bool chmax(T& a, T b) {if (a < b) { a=b; return true; } return false; }
template < class T > inline bool chmin(T& a, T b) {if (a > b) { a=b; return true; } return false; }
#define DEBUG_VLL(vec) REP(sz, vec.size()) std::cerr<<vec[sz]<<(sz==vec.size()-1?'\n':' ');

const long long MOD = 1000000007;
const long long HIGHINF = (long long)1e18;
const int INF = (int)1e9;

ll n, a, b;

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n >> a >> b;
    cout << n / (a + b) * a + min(n % (a + b), a) << '\n';
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <sstream>
#include <stack>
#include <iomanip>
#include <numeric>
#include <string>
#include <cstring>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <queue>
#include <cmath>

#define BEGIN(x) x.begin()
#define END(x) x.end()
#define ALL(x) BEGIN(x), END(x)
#define PAIR make_pair
#define VEC(type) vector<type >
#define endl '\n'

#define FOR(i, A, B) for(auto i = (A);i != (B); i++)
#define FORD(i, A, B) for(auto i = (A);i != (B); i--)

#define READRANGE(begin, end) FOR(it, begin, end) cin >> *it
#define READVEC(V) READRANGE(BEGIN(V), END(V))

using namespace std;

typedef long long lint;
typedef pair<int, int> Pii;
typedef pair<int, lint> Pil;
typedef pair<lint, lint> Pll;
typedef pair<lint, int> Pli;

template<class U, class V>
istream& operator >>(istream& in, pair<U, V>& pr) {
    return in >> pr.first >> pr.second;
}

template<class U, class V>
ostream& operator <<(ostream& out, pair<U, V>& p) {
    return out << p.first << " " << p.second;
}

template<class T>
ostream& operator <<(ostream& out, vector<T> vec) {
    for (T& e : vec)
        out << e << " ";
    return out << endl;
}

// ---- BEGIN LIBRARY CODE ----
// ---- END LIBRARY CODE ----
void io_init()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
};

int main(int argc, char **argv)
{
    io_init();

    // Actual program code starts here.
    int N, K;
    cin >> N >> K;
    VEC(int) H(N);
    READVEC(H);

    sort(ALL(H), greater<int>());
    K = min(K, N);
    lint ret = 0;
    FOR(i, K, N)
        ret += H[i];
    cout << ret << endl;
    return 0;
};

Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;
inline int read() {
    int X=0,w=0;
    char ch=0;
    while(!isdigit(ch)) {
        w|=ch=='-';
        ch=getchar();
    }
    while(isdigit(ch)) X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
    return w?-X:X;
}
inline double dbread() {
    double X=0,Y=1.0;
    int w=0;
    char ch=0;
    while(!isdigit(ch)) {
        w|=ch=='-';
        ch=getchar();
    }
    while(isdigit(ch)) X=X*10+(ch^48),ch=getchar();
    ch=getchar();
    while(isdigit(ch)) X+=(Y/=10)*(ch^48),ch=getchar();
    return w?-X:X;
}
inline void write(int x) {
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
int main()
{
    int a;
    a=read();
    if(a/10==9||a%10==9)
      cout<<"Yes"<<endl;
    else
      cout<<"No"<<endl;
    return 0;
}

Measured memory_bytes: 384
H,W=map(int,input().split())
a = int(input())
x = list(map(int,input().split()))

st = x[0]
m = 1
X=0
for i in range(H):
    s = ""
    for j in range(W):
        if X == st:
            st = x[m]
            m += 1
            X = 0
        if i%2==0:
            s+=str(m)+" "
        else:
            s = str(m)+" "+s
        X +=1
    print(s)



Measured memory_bytes: 3188
///*****************************************************///
///*.......................Faiyaj Bin Amin............................*///
///*...................................................................*///
///*.........................KUET CSE 2K17......................*///
///*...................................................*///
///*****************************************************///

#include<bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>

#define fastio      ios_base::sync_with_stdio(0);cin.tie(0),cout.tie(0)
#define ret return
#define rep(q, i, n) for(int q=i; q<n; q++)
#define forn(i, n) for(int i=0; i<n; i++)
#define mems(a,x) memset(a,x,sizeof(a))
#define ll long long
#define pb push_back
#define em emplace_back
#define mp make_pair
#define all(v) (v).begin(), (v).end()
#define ff first
#define ss second
#define pii pair<int,int>
#define pdd pair<double, double>

#define see(x)        cerr<< __LINE__ << ": " << (#x) << " is "<< (x) <<'\n';
#define seecontent(v) for(auto x : v) { cout << x << " ";} cout << "\n\n";

#define PI 2*acos(0.0)
#define lcm(a, b)  ((a / __gcd(a, b) ) * b)

#define filein freopen ("input.txt", "r", stdin)
#define fileout freopen ("output.txt", "w", stdout)

#define mx 100005
#define INF 1e18
#define MOD 1000000007
#define MIN 0

//template <typename T>  using orderedSet =
//    tree<T, null_type, less_equal<T>,
//    rb_tree_tag, tree_order_statistics_node_update>; //find_by_order, order_of_key


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

/**------------------------------------BITMASK------------------------------------------**/
//int Change(int N, int pos){return N= N^(1<<pos);}
//bool Check(int N, int pos){return (bool)(N &(1<<pos));}  /// check bit 0 or 1
/**-----------------------------------------------------------------------------------------------**/

//using namespace __gnu_pbds;
using namespace std;

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

    int a, sum=0;
    pair<int,int>  v[n];
    forn(i, n)
    {
        cin>>a;
        v[i].ff=a;
    }
    forn(i, n)
    {
        cin>>a;
        v[i].ss=a;
    }

    forn(i, n)
    {
        if(v[i].ff>v[i].ss)
            sum+=v[i].ff-v[i].ss;
    }
    cout << sum << "\n";

    return 0;
}




Measured memory_bytes: 3600
using System;
using System.Linq;

namespace ABC124_B
{
    class Program
    {
        static void Main(string[] args)
        {
            var n = int.Parse(Console.ReadLine());
            var H = Console.ReadLine().Split().Select(int.Parse).ToArray();
            var ans = 0;
            var h = H[0];
            for (int i = 0; i < n; i++)
            {
                if (h <= H[i])
                {
                    ans++;
                    h = H[i];
                }
            }
            Console.WriteLine(ans);
        }
    }
}


Measured memory_bytes: 13268
#include<bits/stdc++.h>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
	freopen ("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int a, b, c, k, total = 0;
	cin >> a >> b >> c >> k;
	if (a >= k) {
		total += k;
		cout << total << endl;
		return 0;
	}
	else {
		total += a;
		k -= a;
	}
	if (b >= k) {
		cout << total << endl;
		return 0;
	}
	else {
		k -= b;
	}
	if (c >= k) {
		total += -k;
		cout << total << endl;
		return 0;
	}
	else {
		total += a;
		k -= a;
	}
	return 0;
}

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

ll gcd(ll a,ll b){
  while(b!=0){
    a%=b;
    swap(a,b);
  }
  return a;
}

ll kaizyou(ll N){
  ll num=1;
  for(ll i=1;i<=N;i++){
  num*=i;
  }
  return num;
}

int dy[]={-1,0,1,0};
int dx[]={0,-1,0,1};

 
int main(){
  int N,K;
  cin >> N >> K;
  int ans=1;
  int num=K;
  while(N/num!=0){
    num*=K;
    ans++;
  }
  cout << ans << endl;
}
      
  
  
  

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
 
#define rep(i,n) for(int i=0;i<(n);i++)
#define REP(i,n) for(int i=1;i<=(n);i++)
#define mp make_pair
#define pb push_back
#define fst first
#define snd second
typedef long long ll;
typedef pair<int,int> pii;

int w,h,n;
struct pnt{int x,y;}a[300007];
bool cmp(pnt x,pnt y){return x.x<y.x;}
pnt su[300007],sd[300007];int ut,dt;
int hu[300007],hd[300007];

struct segt
{
	int s[1200007];int tag[1200007];
	void pu(int x){s[x]=max(s[x+x],s[x+x+1]);}
	void upd(int x,int y){s[x]+=y; tag[x]+=y;}
	void pd(int x){if(tag[x]){upd(x+x,tag[x]); upd(x+x+1,tag[x]); tag[x]=0;}}
	void init(){memset(s,0,sizeof(s));memset(tag,0,sizeof(tag));}
	void modify(int x,int l,int r,int l2,int r2,int val)
	{
		if(l2<=l&&r<=r2){upd(x,val);return;}
		int mid=(l+r)/2;pd(x);
		if(l2<=mid)modify(x+x,l,mid,l2,r2,val);
		if(r2>mid)modify(x+x+1,mid+1,r,l2,r2,val);
		pu(x);
	}
	int query(int x,int l,int r,int l2,int r2)
	{
		if(l2<=l&&r<=r2)return s[x];
		int mid=(l+r)/2;pd(x);
		if(r2<=mid)return query(x+x,l,mid,l2,r2);
		if(l2>mid)return query(x+x+1,mid+1,r,l2,r2);
		return max(query(x+x,l,mid,l2,r2),query(x+x+1,mid+1,r,l2,r2));
	}
}seg;

int solve()
{
	int ans=0;a[0].x=a[0].y=0;a[n+1].x=w;a[n+1].y=h;
	REP(i,n) hu[i]=0,hd[i]=h;
	REP(i,n) if(a[i].y<=h/2) hu[i]=max(hu[i],a[i].y); else hd[i]=min(hd[i],a[i].y);
	seg.init();seg.upd(1,h);ut=dt=0;
	REP(i,n+1)
	{
		seg.modify(1,0,n,0,i-1,a[i].x-a[i-1].x);
		ans=max(ans,seg.query(1,0,n,0,i-1));
		while(ut&&su[ut].y<=hu[i])
		{
			seg.modify(1,0,n,su[ut-1].x,su[ut].x-1,su[ut].y-hu[i]);
			ut--;
		}
		while(dt&&sd[dt].y>=hd[i])
		{
			seg.modify(1,0,n,sd[dt-1].x,sd[dt].x-1,hd[i]-sd[dt].y);
			dt--;
		}
		seg.modify(1,0,n,i-1,i-1,hd[i]-hu[i]-h);
		su[++ut]=(pnt){i,hu[i]};
		sd[++dt]=(pnt){i,hd[i]};
	}
	return ans;
}

int main()
{
	cin>>w>>h>>n;REP(i,n) cin>>a[i].x>>a[i].y;sort(a+1,a+n+1,cmp);
	int ans=solve();swap(w,h);REP(i,n) swap(a[i].x,a[i].y);sort(a+1,a+n+1,cmp);ans=max(ans,solve());
	cout<<ans*2<<endl;return 0;
}

Measured memory_bytes: 18944
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;

const double TL = 1.5 * CLOCKS_PER_SEC;
mt19937 rng((unsigned int) chrono::steady_clock::now().time_since_epoch().count());
#define clr(x, y) memset(x, y, sizeof(x))
#define forn(i, n) for (int i = 0; i < n; i++)
#define LL long long

const int inf = 1e9;
int n, m, k;
char s[20][1005];

int main() {
  //auto start_clock = clock();
#ifdef LOCAL
  freopen("in", "r", stdin);
#endif
  scanf("%d%d%d", &n, &m, &k);
  for(int i = 0; i < n; i++) {
    scanf("%s", s[i]);
  }

  int ans = inf;
  for(int i = 0; i < (1 << (n - 1)); i++) {
    int t = 0;
    vector<int> idx(n, 0);
    idx[0] = 0;
    for(int j = 0; j < n - 1; j++) {
      if((i >> j) & 1) {
        t += 1;
      }
      idx[j + 1] = t;
    }
    vector<int> p(t + 1, 0);
    vector<int> q(t + 1, 0);
    for(int j = 0; j < m; j++) {
      bool out = false, ok = true;
      for(int l = 0; l < (int)q.size(); l++) q[l] = 0;
      for(int l = 0; l < n; l++) {
        if(s[l][j] == '1') {
          p[idx[l]] += 1; 
          q[idx[l]] += 1;
          if(p[idx[l]] > k) {
            out = true;
          }
          if(q[idx[l]] > k) {
            ok = false;
          }
        }
      }
      if(!ok) {
        t = inf;
        break;
      }
      if(out) {
        t += 1;
        p = q;
      }
    }
    ans = min(ans, t);
  }
  printf("%d\n", ans);

  return 0;
}


Measured memory_bytes: 256
import sys
tmp = sys.stdin.readline().strip().split(" ")
n = int(tmp[0])
m = int(tmp[1])
xs = sys.stdin.readline().strip().split(" ")
ys = sys.stdin.readline().strip().split(" ")

s_x=0
s_y=0
r = pow(10,9)+7

for i in range(1,n+1):
	s_x = (s_x + (2*i-1-n)*int(xs[i-1])) % r

for i in range(1,m+1):
	s_y = s_y + (2*i-1-m)*int(ys[i-1]) % r

print((s_x*s_y)%r)


Measured memory_bytes: 18624
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
struct Fast { Fast() { cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20);} } fast;
 
 
int main() {
    int a, b;
    cin >> b >> a;
    if (b > 2 * a){
        cout << b - 2 * a << endl;
    }else{
        cout << 0 << endl;
    }
}

Measured memory_bytes: 256
#pragma GCC optimize("O3")
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("unroll-loops")

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds; 

#define int long long
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define all(v) (v).begin(),(v).end()
#define f first
#define s second
#define sz(x) int(x.size())
#define endl '\n'
#define forn(i,n) for(int i=0;i<n;++i)
#define fore(i,l,r) for(int i=int(l);i<=int(r);++i)
#define rep(i,begin,end) for(__typeof(end) i=(begin);i!=(end);i++)
#define fill(a,value) memset(a,value,sizeof(a));
#define gcd(a,b) __gcd((a),(b))
#define watch1(x) cout << (x) << endl
#define watch2(x,y) cout << (x) << " " << (y) << endl
#define watch3(x,y,z) cout << (x) << " " << (y) << " " << (z) << endl
#define fastio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
 
typedef long long ll;
typedef long double ld; 
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vpii;
typedef tree<pii,null_type,less<pii>,rb_tree_tag,tree_order_statistics_node_update> oset;

// find_by_order(k) returns iterator to kth element starting from 0;
// order_of_key(k) returns count of elements strictly smaller than k;

const int mod = 998244353;
const int inf = 9e18;
const int N = 1e5 + 5;

void solve(){
    int i,k;
    cin>>k;
    vector<int> v;
    queue<int> q;
    for(i=1;i<10;++i){
        v.pb(i);
        q.push(i);
    }
    for(i=0;i<k;++i){
        int num=q.front();
        q.pop();
        int d=num%10;
        if(d!=0){
            v.pb(10*num+d-1);
            q.push(10*num+d-1);
        }
        v.pb(10*num+d);
        q.push(10*num+d);
        if(d!=9){
            v.pb(10*num+d+1);
            q.push(10*num+d+1);
        }
    }
    cout<<v[k-1];
}

signed main(){
    fastio;
    int t;
    //cin>>t;
    t=1;
    while(t--){
        solve();
    }
    return 0;
}

Measured memory_bytes: 7664
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b[100];
cin>>a;
for(int i=0;i<a;i++)
{ cin>>b[i];}
int ret=1000000007;
for(int i=-100;i<101;i++){
	int tmp=0;
	for(int j=0;j<a;j++){
		tmp+=(b[j]-i)*(b[j]-i);
	}
	ret=min(ret,tmp);
} 
cout<<ret;
return 0;
} 


Measured memory_bytes: 256
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

P = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))


# 解説AC


def mod_invs(max, mod):
    """
    逆元のリスト 0 から max まで
    :param int max:
    :param int mod:
    """
    invs = [1] * (max + 1)
    for x in range(2, max + 1):
        invs[x] = (-(mod // x) * invs[mod % x]) % mod
    return invs


def get_ncrs(n, mod):
    """
    nC_0, nC_1, nC_2, ..., nC_n までのリスト
    :param n:
    :param mod:
    :return:
    """
    invs = mod_invs(n, mod)
    ret = [1]
    ncr = 1
    for i in range(1, n + 1):
        ncr = ((ncr * (n - i + 1) % mod) * invs[i]) % mod
        ret.append(ncr)
    return ret


ncr = get_ncrs(P - 1, P)


def poly(j):
    # 1 - (x-j)^(P-1) は x == j のときだけ 1、それ以外のとき 0 になる
    # 1 - (x-j)^(P-1) の係数
    coef = []
    c = 1
    for i in range(P):
        coef.append(-ncr[i] * c)
        c = c * -j % P
    coef.reverse()
    coef[0] += 1
    return coef


ans = [0] * P
for j, a in enumerate(A):
    if a == 1:
        for k, b in enumerate(poly(j)):
            ans[k] += b
            ans[k] %= P
print(*ans)

#
# def f(x, B):
#     ret = 0
#     for i, b in enumerate(B):
#         ret += b * x ** i
#         ret %= P
#     return ret
#
#
# hist = []
# for B in itertools.product(range(P), repeat=P):
#     r = []
#     for x in range(P):
#         a = f(x, B)
#         r.append(a)
#     if [a for a in r if a >= 2]:
#         continue
#     hist.append((r, list(B)))
# hist.sort()
# for r, B in hist:
#     print('a: {}, b: {}'.format(r, B))
# print()
#
# # for P in [2, 3, 5, 7, 11, 13, 17, 19, 23]:
# for P in [3, 5, 7]:
#     print(P)
#     t = []
#     # x_i mod P
#     for x in range(P):
#         s = []
#         for e in range(P):
#             s.append(x ** e % P)
#             # s.append(x ** e)
#         print(x, s)
#         t.append(s)
#     ss = []
#     for x in range(P):
#         s = 0
#         for i in range(P):
#             s += t[i][x]
#         ss.append(s % P)
#     print('s', ss)
#     print()


Measured memory_bytes: 48604
#include<iostream>
#include<string>

using namespace std;

int main(){
    string n;
    cin >> n;
    int ans = 0;
    bool flag = false;
    for(int i = n.size() - 1; i >= 0; i--){
        if ('6' <= n[i] && n[i] <= '9' && !flag) {
            ans += 10 - (int)(n[i] - '0');
            flag = true;
        }else if ('6' <= n[i] && n[i] <= '9' && flag) {
            ans += 9 - (int)(n[i] - '0');
        }else if (n[i] == '5' && !flag) {
            if (i == 0){
                ans += 5;
            }else if (i > 0 && '0' <= n[i-1] && n[i-1] <= '4') {
                ans += 5;
            }else if('5' <= n[i] && n[i] <= '9'){
                ans += 5;
                flag = true;
            }
        }else if (n[i] == '5' && flag) {
            ans += 4;
        }else if ('0' <= n[i] && n[i] <= '4' && !flag){
            ans += (int)(n[i] - '0');
        }else if ('0' <= n[i] && n[i] <= '3' && flag){
            ans += (int)(n[i] - '0') + 1;
            flag = false;
            // cout << ans << '\n';
        }else if (n[i] == '4' && flag) {
            if (i > 0 && '5' <= n[i-1] && n[i-1] <= '9') {
                ans += 5;
            }else{
                ans += (int)(n[i] - '0') + 1;
                flag = false;
            }
            
            
            
        }
        
        
    }
    if (flag) {
        ans += 1;
    }
    cout << ans << "\n";
}

Measured memory_bytes: 1412
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<limits>
#include<iomanip>
#include<cmath>
#include<climits>

using namespace std;

#define rep(i,m,n) for(int i=m;i<n;i++) 
#define sort(a) sort(a.begin(),a.end())
#define reverse(a) reverse(a.begin(),a.end())
#define all(a) a.begin(),a.end()


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

const int mod=1e9+7;

int gcd(int a,int b){
    if(b==0){
        return a;
    }else{
        return gcd(b,a%b);
    }
}
int main(){
    int n;
    ll W,w_0=INT_MAX;
    cin >> n >> W;
    vector< pair<ll,ll> > vw(n);

    rep(i,0,n){
        ll w,v;
        cin >> w >> v;
        vw[i]=make_pair(v,w);
        w_0=min(w_0,w);
    }

    sort(vw);
    reverse(vw);

    ll ans=0;
    rep(w0,0,n+1){
        rep(w1,0,n-w0+1){
            rep(w2,0,n-w0-w1+1){
                ll Vsum=0,Wsum=0;
                int w3=n-w0-w1-w2;
                int cnt0=0,cnt1=0,cnt2=0,cnt3=0;
                rep(i,0,n){
                    if(vw[i].second==w_0&&cnt0<w0&&Wsum+vw[i].second<=W){
                        cnt0++;
                        Vsum+=vw[i].first;
                        Wsum+=vw[i].second;
                    }else if(vw[i].second==w_0+1&&cnt1<w1&&Wsum+vw[i].second<=W){
                        cnt1++;
                        Vsum+=vw[i].first;
                        Wsum+=vw[i].second;
                    }else if(vw[i].second==w_0+2&&cnt2<w2&&Wsum+vw[i].second<=W){
                        cnt2++;
                        Vsum+=vw[i].first;
                        Wsum+=vw[i].second;
                    }else if(vw[i].second==w_0+3&&cnt3<w3&&Wsum+vw[i].second<=W){
                        cnt3++;
                        Vsum+=vw[i].first;
                        Wsum+=vw[i].second;
                    }
                }
                ans=max(ans,Vsum);
            }
        }
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 256
import numpy as np
#入力ABCX
A = input()
B = input()
C = input()
X = input()
#50円玉の取り得る場合の数
fifty = np.array([i for i in range(int(C)+1)])
#100円玉の取り得るお金と50円の取り得るお金の和(2次元)
hun = np.array([100 * i + 50 * fifty for i in range(int(B)+1)])
#100円玉の取り得るお金と50円の取り得るお金の和を(1次元)
hun_r = np.ravel(hun)
#500円玉の取り得るお金と100円玉の取り得るお金と50円の取り得るお金の和(2次元)
f_hun = np.array([500 * i + hun_r for i in range(int(A)+1)])
#条件に合う数
print(len(f_hun[f_hun == int(X)]))


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

int main() {
        ios_base:: sync_with_stdio(0);
        cin.tie(0);
        cout.tie(0);
        int n;
        cin >> n;
        vector<pair<int, int> > jobs(n);
        for(int i = 0; i < n; i++)
                cin >> jobs[i].second >> jobs[i].first;
        sort(jobs.begin(), jobs.end());
        int curt = 0;
        for(int i = 0; i < n; i++) {
                int reqt = curt + jobs[i].second;
                if(reqt <= jobs[i].first)
                        curt = reqt;
                else {
                        cout << "No";
                        return 0;
                }
        } 
        cout << "Yes";
        return 0;
}

Measured memory_bytes: 1792
s=input().split()
money,num=int(s[0]),int(s[1])
no_list=input().split()
while True:
    flag=0
    for money_element in list(str(money)):
        if money_element in no_list:
            flag=1
            money+=1
            break
    if flag==0:
        print(money)
        break












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

int height[90001];
int width[90001];
long long diff[90001];

long long func(int a, int b, int d){
  if (a == b) return 0;
  return diff[b] - diff[a];
}

int main(){
  int h, w, d; scanf("%d %d %d", &h, &w, &d);

  for (int i = 0; i < h; i++){
    for (int j = 0; j < w; j++){
      int p;
      scanf("%d\n", &p);
      height[p] = i;
      width[p] = j;
    }
  }

  for (int i = 1; i + d <= h * w; i++){
    if (i <= d) diff[i] = 0;
    diff[i + d] = abs(height[i] - height[i+d]) + abs(width[i] - width[i+d]) + diff[i];
  }

  int q; scanf("%d", &q);
  for (int i = 0; i < q; i++){
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%lld\n", func(a, b, d));
  }

  return 0;
}

Measured memory_bytes: 2560
#include<iostream>

using namespace std;

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

	int a[n+2];
	
	a[0]=a[n+1]=0;

	for(int i=2;i<=n+1;i++)
		cin >> a[i-1];

	long long sum = 0;
	for(int i=2;i<=n+2;i++)
	{
		sum+=abs(a[i-1]-a[i-2]);
	}
	
	int dif = 0;
	for(int i=2;i<=n+1;i++)	
	{
		dif=(abs(a[i-1]-a[i-2])+abs(a[i]-a[i-1])-abs(a[i]-a[i-2]));
		cout << sum - dif << endl;
	}

}

Measured memory_bytes: 1664
from collections import defaultdict
H, N= map(int,input().split())
A = []
B = []
for i in range(N):
    a,b = map(int,input().split())
    A.append(a)
    B.append(b)

dp = [10**10]*(H+1)
dp[0] = 0

for i in range(0,N):
    a = A[i]
    b = B[i]
    for h in range(H+1-a):
        dp[h+a] = min(dp[h+a], dp[h] + b)
    dp[H] = min(dp[H], min(dp[H-a:H])+b)

print(dp[H])


Measured memory_bytes: 41436
#include <bits/stdc++.h>
using namespace std;
#define repr(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) for(int i=0;i<n;i++)
#define reprrev(i,a,b) for(int i=b-1;i>=a;i--)
#define reprev(i,n) reprrev(i,0,n)
typedef long long ll;
typedef unsigned long long ull;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
 
/* attention
    long longのシフト演算には気をつけよう
    タイポした時のデバッグが死ぬほどきつくなるので変数名は最低3字くらい使った方がいいかも
    sizeは(int)とキャストしよう
    ごちゃごちゃ場合分けを考える前に全探索は考えましたか？
    cin.tie(0);
    ios::sync_with_stdio(false);<- これら、printfとかと併用しない方が良さそう

*/

const ll mod = 1e9+7;

void chmod(ll &M){
    if(M >= mod) M %= mod;
    else if(M < 0){
        M += (abs(M)/mod + 1)*mod;
        M %= mod;
    }
}

int getl(int i, int N) { return i==0? N-1:i-1; };
int getr(int i, int N) { return i==N-1? 0:i+1; };

/* <--------------------------------------------> */


// cf https://www.creativ.xyz/segment-tree-abstraction-979/
template < class T > 
class SegTree{                      
    int n;                          // 葉の数
    vector<T> data;                 // データを格納するvector
    T def;                          // 初期値かつ単位元
    function<T(T, T)> operation;    // 区間クエリで使う処理
    function<T(T, T)> update;       // 点更新で使う処理


    // 区間[a, b)の総和。ノード k=[l, r) に着目している。
    T _query(int a, int b, int k, int l, int r){
        if(r <= a || b <= l) return def;
        if(a <= l && r <= b) return data[k];
        else{
            T c1 = _query(a, b, 2*k+1, l, (l+r)/2);
            T c2 = _query(a, b, 2*k+2, (l+r)/2, r);
            return operation(c1, c2);
        }

    }

    public:
        // _n:必要サイズ, _def:初期値かつ単位元, _operaotion:クエリ関数
    // _update:更新関数
        SegTree(size_t _n, T _def, function<T(T, T)> _operation, function<T(T, T)> _update)
            : def(_def), operation(_operation), update(_update) {
            n = 1;
            while(n < _n) n *= 2;
            data = vector<T>(2*n-1, def);
        }

        // [a, b) の区間クエリを実行
        T query(int a, int b){
            return _query(a, b, 0, 0, n);
        }

        // 場所 i(0-indexed) の値を x で更新
        void change(int i, T x){
            i += n-1;
            // 点加算なら [](T d, T x){ return d+x; }, 点更新なら [](T d, T x){ return x; }
            data[i] = update(data[i], x);
            while(i > 0){
                i = (i-1)/2;
                data[i] = operation(data[i*2+1], data[i*2+2]); 
            }
        }

        T operator[](int i){ return data[i+n-1]; }
};


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

    int n, q; cin >> n >> q;
    SegTree<ll> seg(n, (1LL<<31)-1, [](ll x, ll y){ return min(x, y); }, [](ll d, ll x){ return x; });

    while(q--){
        int com; cin >> com;
        if(com == 0){
            int x, y; cin >> x >> y;
            seg.change(x, y);
        }
        else{
            int x, y; cin >> x >> y;
            cout << seg.query(x, y+1) << endl;
        }
    }
    
    return 0;
}


Measured memory_bytes: 4960
n,k = map(int,input().split())
s = input()
ms = 0
ps = 0
temp = [0]
if s[0] == "0":
    temp.append(0)
for i in s:
    # print(i,ps,ms)
    if i == "0":
        ms += 1
        if ps:
            temp.append(ps)
            ps = 0
    else:
        ps += 1
        if ms:
            temp.append(ms)
            ms = 0
if ms:
    temp.append(ms)
else:
    temp.append(ps)
# print(temp)
temp.append(0)
for i in range(len(temp)-1):
    temp[i+1] += temp[i]
# print(temp)
ans = 0
if len(temp)-(2*k+1) <= 0:
    ans = temp[-1]
else:
    for i in range(0,len(temp)-(2*k+1),2):
        ans = max(ans,temp[i+2*k+1]-temp[i])
print(ans)

Measured memory_bytes: 13012
#include <stdio.h>
#include <iostream>
#include <cstdio>
using namespace std;
int x, c=0;
void dfs(int pos) {
	if (pos == 1) {
		c++;
		return;
	}else if (pos == 2) {
		c = c + 2;
		return;
	}
	else if (pos == 3) {
		c = c + 4;
		return;
	}
	else {
		dfs(pos - 1);
		dfs(pos - 2);
		dfs(pos - 3);
	}


}

int main() {
	while (1) {
	int	days = 0, years = 0;
	c = 0;
	cin >> x;
	if (x == 0) {
		break;
	}
	dfs(x);
	days = c / 10;
	if (c % 10 != 0) {
		days++;
	}
	years = days / 365;
	if (days % 365 != 0) {
		years++;
	}
	cout << years << endl;
	}
	

}

Measured memory_bytes: 1160
N = int(input())
flag = False
for i in range(1,3500):
    for j in range(1,3500):
        if((4*i*j - N*i - N*j) > 0 and (N*i*j)%(4*i*j - N*i - N*j) == 0):
            w = int((N*i*j)/(4*i*j - N*i - N*j))
            h = i
            n = j
            flag = True
            break
    if flag:
        break

print(h,n,w)

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

void func(string&s) {
	int d = 0;
	while ((d = (int)s.find("_", d)) >= 0)s[++d] = toupper(s[d]);
	s.erase(remove(s.begin(), s.end(), '_'), s.end());
}
int main() {
	string s, m;
	while (cin >> s >> m, m != "X") {
		if (m == "U") {
			func(s);
			s[0] = toupper(s[0]);
		}
		if (m == "L") {
			func(s);
			s[0] = tolower(s[0]);
		}
		if (m == "D") {
			s[0] = tolower(s[0]);
			rep(i, s.size()) {
				if (isupper(s[i])) {
					s.insert(i, "_"); i++;
				}
			}
			transform(s.begin(), s.end(), s.begin(), ::tolower);
		}
		cout << s << endl;
	}
}

Measured memory_bytes: 2996