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


int main(){

    int n,m,x;
    cin >> n >> m >> x;

    int a[m];
    for(int i=0; i<m; i++){
        cin >> a[i];
    }

    sort(a, a+m);
    int total1 = 0;
    for(int i=0; i<m; i++){
        if(a[i] < x){
            total1 ++;
        }else{
            break;
        }
    }

    int total2 = 0;
    for(int i=m-1; i>=0; i--){
        if(a[i] > x){
            total2++;
        }else{
            break;
        }
    }

    cout << min(total1, total2) << endl;
    return 0;
}

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

struct node{
  struct node *R;
  struct node *L;
  struct node *parent;
  int key;
};

typedef struct node * Node;

Node root;

Node tMin(Node);
Node tMax(Node);
Node tSea(Node,int);
Node tSor(Node);
void tDel(Node);
void insert(int);
void inorder(Node);
void preorder(Node);

int main()
{
  int n, i, x;
  char meirei[20];
  
  scanf("%d",&n);/*命令数入力*/
  
  for (i=0;i<n;i++)
    {
      scanf("%s",meirei);/*何の命令か入力*/
      
      if (meirei[0]=='f')/*findが入力された場合*/
	{
	  scanf("%d",&x);/*探す数入力*/
	  
	  Node t = tSea(root,x);/*xがあるかどうか探す*/
	  if ( t != NULL ) printf("yes\n");
	  else printf("no\n");
	}
      else if (meirei[0]=='i')/*insertが入力された場合*/
	{
	  scanf("%d", &x);
	  insert(x);/*二分木にroot追加*/
	}
      else if ( meirei[0] == 'p' )/*printが入力された場合*/
	{
	  inorder(root);/*中間順巡回*/
	  printf("\n");
	  preorder(root);/*先行順巡回*/
	  printf("\n");
	}
      else if ( meirei[0] == 'd' )/*dereteが入力された場合*/
	{
	  scanf("%d", &x);
	  tDel(tSea(root, x));/*削除*/
	}
    }

  return 0;
}

Node tMin(Node x)
{
  while(x->L!=NULL)
    {
      x=x->L;
    }
  return x;
}

Node tMax(Node x)
{
    while(x->R!=NULL)
    {
      x=x->R;
    }
  return x;
}

Node tSea(Node x, int k)
{
  if(x==NULL||k==x->key)return x;
  if(k<x->key)return tSea(x->L,k);
  else return tSea(x->R,k);
}

Node tSor(Node x)
{
  Node y;
  
  if(x->R!=NULL)return tMin(x->R);

  y=x->parent;
  while(y!=NULL&&x==y->R)
    {
      x=y;
      y=y->parent;
    }
  return y;
}

void tDel(Node z)
{
  Node y; // node to be deleted
  Node x; // child of y

  if(z->L==NULL||z->R==NULL)y=z;
  else y=tSor(z);

  if(y->L!=NULL)x=y->L;
  else x=y->R;

  if(x!=NULL)x->parent=y->parent;
  if(y->parent==NULL)root=x;
  else if(y==y->parent->L)y->parent->L=x;
  else  y->parent->R=x;

  if(y!=z)z->key=y->key;
}

void insert(int k)
{
  Node y = NULL;
  Node x = root;
  Node z;

  z = malloc(sizeof(struct node));
  
  z->key = k;
  z->L = NULL;
  z->R = NULL;

  while(x!=NULL)
    {
      y=x;
      if(z->key<x->key)x=x->L;
      else x=x->R;
    }
  z->parent=y;

  if(y==NULL)root=z;
  else if(z->key<y->key)y->L=z;
  else y->R=z;
}

void inorder(Node u)
{
  if(u==NULL)return;
  
  inorder(u->L);
  printf(" %d",u->key);
  inorder(u->R);
}
void preorder(Node u)
{
  if(u==NULL)return;
  printf(" %d",u->key);
  preorder(u->L);
  preorder(u->R);
}



Measured memory_bytes: 20552
#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
using P = pair<ll, ll>; // cost, node
using T = tuple<ll, ll, ll>; // x, y, node
const int N = 1e5+9;

struct graph {
    bool used = false;
    vector<P> next;
};

int n;
T xp[N];
T yp[N];
graph g[N];

int main() {
    cin >> n;
    for(int i = 1; i <= n; i++) {
        ll x, y;
        cin >> x >> y;
        xp[i] = T(x, y, i);
        yp[i] = T(y, x, i);
    }
    sort(&xp[1], &xp[n+1]);
    sort(&yp[1], &yp[n+1]);

    for(int i = 1; i <= n-1; i++) {
        ll x1, y1, n1;
        ll x2, y2, n2;
        tie(x1, y1, n1) = xp[i];
        tie(x2, y2, n2) = xp[i+1];
        g[n1].next.push_back(P(abs(x1 - x2), n2));
        g[n2].next.push_back(P(abs(x1 - x2), n1));
    }

    for(int i = 1; i <= n-1; i++) {
        ll y1, x1, n1;
        ll y2, x2, n2;
        tie(y1, x1, n1) = yp[i];
        tie(y2, x2, n2) = yp[i+1];
        g[n1].next.push_back(P(abs(y1 - y2), n2));
        g[n2].next.push_back(P(abs(y1 - y2), n1));
    }

    priority_queue<P, vector<P>, greater<P>> que;
    g[1].used = true;
    for(auto x : g[1].next)  que.push(x);
    ll ans = 0;
    while(!que.empty()) {
        ll cost, node;
        tie(cost, node) = que.top(); que.pop();
        if(g[node].used)  continue;
        g[node].used = true; ans += cost;
        for(auto x : g[node].next)  que.push(x);
    }
    cout << ans << endl;
}

Measured memory_bytes: 23280
#include <bits/stdc++.h>
using namespace std;
int n,t;
const int maxn=1e5+100;
int a[maxn];
priority_queue < int > q;
int maxv=0,maxs=0;
void solve_B(){
	cin >> n >> t;
	cin >> a[1];
	q.push(-a[1]);
	for (int i=2;i<=n;i++){
		cin >> a[i];
		int u=-q.top();
		if (a[i]-u>maxv){
			maxv=a[i]-u;
			maxs=1;
		}else if (a[i]-u==maxv){
			maxs++;
		}
		q.push(-a[i]);
	}
	cout << maxs;
}
int main(){
	solve_B();
	return 0;
}

Measured memory_bytes: 1148
import java.util.Scanner;

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

	int N = sc.nextInt();
	int M = sc.nextInt();

	if (N == M)
	    System.out.println("Yes");
	else
	    System.out.println("No");

    }
}

Measured memory_bytes: 23764
def cmb(n,r,mod=10**9+7):
    if r<0 or r>n:return 0
    return g1[r]*g2[r]%mod


mod=10**9+7
n,a,b=map(int,input().split())
k=max(a,b)
g1=[1,n]
g2=[1,1]
inverse=[0,1]

for i,j in enumerate(range(n-1,((n-k+1)-1),-1)):
    i=i+2
    g1.append((g1[-1]*j)%mod)
    inverse.append((-inverse[mod%i]*(mod//i))%mod)
    g2.append((g2[-1]*inverse[-1]%mod))

print((2**n-1-cmb(n,a)-cmb(n,b))%mod)

Measured memory_bytes: 287576
r, c = gets.split.map(&:to_i)
sum_arr = Array.new(c+1, 0)
ARGF.each_line do |line|
  arr = line.split.map(&:to_i)
  arr << arr.inject(:+)
  puts arr.join("\s")
  (c+1).times do |i|
    sum_arr[i] += arr[i]
  end
end

puts sum_arr.join("\s")

Measured memory_bytes: 6120
#!/usr/bin/env python3
import sys
import heapq
from collections.abc import Iterable
from math import *
from itertools import *
from collections import *
from functools import *
from operator import *
try:
    from math import gcd
except Exception:
    from fractions import gcd


def solve(N: int, K: int, V: "List[int]"):

    lq = []
    acc_l = 0
    acc_ml = []
    ret = 0
    for li in range(min(N+1, K + 1)):
        if 0 < li:
            acc_l += V[li - 1]
            if V[li - 1] < 0:
                acc_ml.append(V[li - 1])

        if ret < acc_l:
            ret = acc_l
        acc_r = 0
        ms = [v for v in acc_ml]
        ms.sort()
        for _ri in range(min(N+1, K + 1) - li):
            if 0 < _ri:
                ri = N - _ri
                acc_r += V[ri]
                if V[ri] < 0:
                    ms.append(V[ri])
                    ms.sort()
            ci = min(len(ms), K - li - _ri)
            acc_c = sum(ms[:ci])
            acc = acc_l + acc_r - acc_c
            if ret < acc:
                ret = acc
    return ret


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    K = int(next(tokens))  # type: int
    V = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    result = solve(N, K, V)
    if isinstance(result, Iterable) and not isinstance(result, str):
        result = '\n'.join([str(v) for v in result])
    print(result)

if __name__ == '__main__':
    main()


Measured memory_bytes: 5372
N, K = map(int, input().split())
sunu = [0]*N
#print(N,K)
for i in range(K):
  D = int(input())
  A = list(map(int, input().split()))
#  print(D)
#  print(A)
  for j in range(D):
    sunu[A[j]-1] = 1
#
#print(sunu)
z = 0
for i in sunu:
  if i == 0:
    z += 1
#
print(z)


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

int main() {
    int H1, H2, M1, M2, K;
    cin >> H1 >> M1 >> H2 >> M2 >> K;
    int T1 = 60 * H1 + M1, T2 = 60 * H2 + M2;
    if (T2 - T1 - K >= 0) {
        cout << T2 - T1 - K << endl;
    }
    else {
        cout << 0 << endl;
    }
}

Measured memory_bytes: 3624
#include<stdio.h>
#include<cstdio>
#include<cmath>
using namespace std;

int main() {
  long long X, Y;
  scanf("%lld %lld", &X, &Y);
  int res = 0;
  long long num = X;
  while (num <= Y) {
    num *= 2;
    res++;
  }
  printf("%d\n", res);
}

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

int main() {
  int n, m;
  string s;
  cin >> n >> m >> s;

  { // check impossible
    map<char, int> ma;
    for (int i = 0; i < m; ++i)
      ++ma[s[i]];
    int i = 0;
    while (i + m < n) {
      if (ma['1'] == m)
        return 0 * puts("-1");
      ++ma[s[i + m]];
      --ma[s[i]];
      ++i;
    }
    if (ma['1'] == m)
      return 0 * puts("-1");
  }

  vector<int> dp(n + 1);
  const int inf = 2e9;
  dp[n] = 0;
  int sz = m;
  map<int, int> ma;
  ++ma[0];
  for (int i = n - 1; i >= 0; --i) {
    // cout << "##### " << i << ' ' << sz << '\n';
    if (s[i] == '1')
      dp[i] = inf;
    else
      dp[i] = ma.begin()->first + 1;
    ++sz;
    ++ma[dp[i]];
    if (i + m <= n) {
      --ma[dp[i + m]];
      if (ma[dp[i + m]] == 0)
        ma.erase(dp[i + m]);
    }
  }

  // dp[0] = sz / m;

  // for (int i = 0; i <= n; ++i)
  //   cout << dp[i] << ' ';
  // cout << '\n';

  int i = 0;
  vector<int> ans;
  while (i < n) {
    for (int j = i + 1; j < i + 1 + m; ++j) {
      if (dp[j] == dp[i] - 1) {
        ans.push_back(j - i);
        i = j;
        // cout << "#### " << j << ' ' << '\n';
        break;
      }
    }
  }

  for (int x : ans)
    cout << x << ' ';
  return 0;
}

Measured memory_bytes: 1528
A, B, C, D = map(int, input().split())
count = 0

while True:
    if(count % 2 == 0):
        C = C - B
        count = count + 1
    else:
        A = A - D
        count = count + 1
    if (A <= 0):
        print("No")
        break

    elif(C <= 0):
        print("Yes")
        break


Measured memory_bytes: 9108
#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++)
typedef long long ll;
typedef pair<int,int> pii;
const int MOD = 1e9+7;


int main(){
    int n,k;
    cin>>n>>k;
    vector<ll> sum(n+1,0);
    ll ans=0;
    REP(i,n){
        sum[i]=sum[i-1]+i;
    }

    for(int i=k;i<=n;i++){
        ans = (ans+sum[n]-sum[n-i]-sum[i-1]+1)%MOD;
    }
    cout<<ans+1<<endl;
    return 0;
}

Measured memory_bytes: 4840
#include <iostream>

int main(int argc, char const* argv[])
{
	int t;
	int h,m,s;
	std::cin >> t;
	h = t / 3600;
	m = t / 60 % 60;
	s = t % 60;

	std::cout << h << ":";
	std::cout << m << ":";
	std::cout << s << "";
	std::cout << std::endl;

	return 0;
}

Measured memory_bytes: 1168
n=int(input())
if n==1:
    print(1)
else:
    r=1+(n*(n+1)//2-1)*2
    for i in range(2, int(n**0.5)+1):
        for j in range(i*i, n+1, i):
            if i**2!=j:
                r+=2*j
            else:
                r=r+j
    print(r)

Measured memory_bytes: 66640
package main

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

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

var sc = bufio.NewScanner(os.Stdin)

func main() {
	sc.Split(bufio.ScanWords)
	n := nextInt()
	A := make([]int, n+1)
	B := make([]int, n+1)
	max := 0
	for i := 0; i < n; i++ {
		A[i] = nextInt()
		if A[i] > max {
			max = A[i]
		}
	}
	C := make([]int, max+1)

	//fmt.Println(A, B, C)
	countingSort(A, B, C, n)

}

func countingSort(A []int, B []int, C []int, n int) {
	//C[A[i]]に、A[i]が出現する回数を記録
	for i := 0; i < n; i++ {
		C[A[i]]++
	}

	//C[i]に、i以下の数の出現数を記録
	for i := 1; i < len(C); i++ {
		C[i] = C[i] + C[i-1]
	}

	//C[A[j]]は、A[j]以下の数の出現回数
	//これは、出力する配列Bでの、A[j]indexを表す
	for j := n - 1; j >= 0; j-- {
		B[C[A[j]]] = A[j]
		C[A[j]]--
	}
	fmt.Println(arrayAsString(B[1:]))
}

func arrayAsString(arr []int) string {
	return strings.TrimRight(fmt.Sprintf("%+v", arr)[1:], "]")
}



Measured memory_bytes: 75684
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#include <map>
typedef long long ll;
#define REP(i, n) for(ll i = 0; i < n; i++)
#define REPR(i, n) for(ll i = n; i >= 0; i--)
#define FOR(i, m, n) for(ll i = m; i < n; i++)
#define INF 2e9
#define ALL(v) v.begin(), v.end()
using Graph = vector<vector<int>>;


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

int main() {
    ll n, k;
    cin >> n >> k;
    ll digits = 0;
    while (true){
        if(n <= 0){
            break;
        }
        digits ++;
        n /= k;
    }
    cout << digits << endl;
}



Measured memory_bytes: 3644
# -*- coding:utf-8 -*-

def solve():
    N, M = list(map(int, input().split()))
    MAX = 10**9
    L, R, D = [], [], []
    for i in range(M):
        _in = list(map(int, input().split()))
        L.append(_in[0])
        R.append(_in[1])
        D.append(_in[2])

    E = [{} for _ in range(N)]
    for i in range(M):
        E[L[i]-1][R[i]-1] = D[i]  # E[x1][x2] := x1からx2までの差
        E[R[i]-1][L[i]-1] = -D[i] # E[x2][x1] := x2からx1までの差
    
    V = [None] * N

    for i in range(N):
        if V[i] is not None:
            continue
        V[i] = 0
        q = [i]
        while q:
            j = q.pop()
            v = V[j]
            for k, d in E[j].items():
                if V[k] is None:
                    V[k] = v+d
                    q.append(k)
    ans = True
    for l, e in enumerate(E):
        for r, d in e.items():
            ans = ans and V[r]-V[l] == d
        if not ans:
            break
    print("Yes" if ans else "No")
        

if __name__ == "__main__":
    solve()


Measured memory_bytes: 82112
n, m = list(map(int, input().split()))
A = [[0 for w in range(m)] for h in range(n)]
B = [0 for h in range(m)]
for i in range(n):
    A[i] = list(map(int, input().split()))
for i in range(m):
    B[i] = int(input())

for i in range(n):
    c = 0
    for j in range(m):
        c += A[i][j] * B[j]
    print(c)

Measured memory_bytes: 7936
#include <iostream>
#include <sstream>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;

int arr[101] = {0};

int main()
{
	string n, m, l;
	cin >> n;
	for(int i=n.length()-1; i>=0; i--)
	{
		m += n[i];
	}
	if(n != m)
	{
		cout << "No";
		return 0;
	}
	for(int i=n.length()/2+1; i<n.length(); i++)
	{
		l += n[i];
	}
	for(int i=0; i<l.length(); i++)
	{
		if(n[i] != l[i])
		{
			cout << "No";
			return 0;
		}
	}
	cout << "Yes";
}



Measured memory_bytes: 3636
#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int main() {
  string s;
  getline(cin, s);
  for (unsigned int i = 0; i < s.length(); i++)
    cout << char(islower(s[i]) ? s[i]-32 : s[i]);
  cout << endl;
  return 0;
}

Measured memory_bytes: 0
#include<stdio.h>
#include<string.h>
int isEmpty(void);
int dequeue(void);
void enqueue(int);

int head=0,tail=0,time[100000];
int main(){
  int zanshi,n,q,i,total=0;
  char name[100000][10];
  scanf("%d%d",&n,&q);

  for(i=0;i<n;i++){
    scanf("%s%d",name[i],&time[i]);
    tail++;
  }
  while(isEmpty()==0){
    if(q>=time[head]){
      total+=dequeue();
      printf("%s ",name[head-1]);
      printf("%d\n",total);
    }
    else{
      strcpy(name[tail],name[head]);
      time[head]-=q;
      zanshi=dequeue();
      enqueue(zanshi);     
      total+=q;
    }
  }
  return 0;
}

int isEmpty(){
  if(head==tail)
    return 1;
  else
    return 0;
}

int dequeue(){
  int x;

  x=time[head];
  if(head+1==100000)
    head=0;
  else
    head=head+1;
  return x;
}

void enqueue(int x){

  time[tail]=x;
  if(tail+1==100000)
    tail=0;
  else
    tail=tail+1;
}
  
  

  



Measured memory_bytes: 3052
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <cassert>
#include <cmath>
#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <queue>
#include <vector>
#include <iostream>
#include <set>
#define MP make_pair
#define F first
#define PB push_back
#define S second
using namespace std;
typedef long long ll;
const int maxn = 2e5 + 50;
const int mod = 1e9 + 7;
const int inf = (1 << 30);
int a[maxn];

int main() {
    ios_base::sync_with_stdio(false);
    ll n, cnt = 0;
    cin >> n;
    ll tmp = 0;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 1; i <= n; i++) {
        cnt += a[i] / 2;
        a[i] %= 2;
        if (a[i] == 1 and a[i + 1] > 0){
            a[i + 1] --;
            cnt ++; 
        }
    }        
    cout << cnt << endl;
}

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define mod 1000000007
#define f(i,a,b) for(ll i=a;i<b;i++)
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ii pair<ll,ll>
#define vii vector<ii>
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define MAX 1e9
 
ll modpow(ll base, ll exp, ll modulus) {base %= modulus;ll result = 1;while (exp > 0) {if (exp & 1) result = (result * base) % modulus;base = (base * base) % modulus;exp >>= 1;}return result;}
const ld pi=acos(-1);


int main(){
    IOS;
    ll a,b,n;cin>>a>>b>>n;
    ll mn=min(b-1,n);
    cout<<(a*mn)/b;
    return 0;  
} 





Measured memory_bytes: 3636
import sys
import numpy as np
import math
import collections
import copy
from collections import deque 
from functools import reduce
from itertools import product

A, B, C = map(int, input().split())
K = int(input())
for p in product((1, 2, 3), repeat=K):
    R, G, BL = A, B, C
    for pi in p:
        if pi == 1:
            R *= 2
        if pi == 2:
            G *= 2
        if pi == 3:
            BL *= 2
    if R < G < BL:
        print("Yes")
        break
else:
    print("No")


























Measured memory_bytes: 27168
from bisect import*
n,*l=map(int,open(0).read().split())
l.sort()
A=0
for i in range(n):
    a=l[i]
    for j in range(i+1,n):
        b=l[j]
        k1=max(j+1,bisect(l,b-a))
        k2=bisect_left(l,a+b)
        A+=max(0,k2-k1)
print(A)

Measured memory_bytes: 49344
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <queue>
#include <tuple>
#include <set>
#include <map>

using namespace std;

int main(void) {
    int N;
    cin >> N;
    vector<int> A(N);
    for(int i=0; i<N; i++) {
        cin >> A[i];
    }

    map<int,int64_t> mp;
    for(int i=0; i<N; i++) {
        mp[i+1-A[i]]++;
    }

    int64_t ans = 0;
    for(int i=0; i<N; i++) {
        mp[i+1-A[i]]--;
        ans += mp[A[i]+i+1];
    }

    cout << ans << endl;

    // map<int, int64_t> mp;
    // for(int i=1; i<=N; i++) {
    //     int A;
    //     cin >> A;
    //     A -= i;
    //     mp[i]++;
    // }

    // int64_t ans = 0;
    // for(auto [key, val]: mp) {
    //     ans += val*(val-1);
    // }

    // cout << ans << endl;
    return 0;
}


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

int main() {
  ll N;
  cin >> N;
  if (N == 0) {
    cout << 0 << endl;
    return 0;
  }
  vector<int> ans(0);
  while (N != 0) {
    int tmp = N % 2;
    if (tmp < 0) tmp += 2;
    N = (N-tmp) / (-2);
    ans.push_back(tmp);
  }
  for (int i = ans.size()-1; i >= 0; i--) cout << ans[i];
  cout << endl;
}


Measured memory_bytes: 3564
#![allow(unused_imports, unused_macros, dead_code)]
use std::f64::*;
use std::cmp::*;
use std::collections::*;

macro_rules! dump{
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

const INF: i64 = 0x3f3f3f3f3f3f3f3f;
const MOD: i64 = 1000000007;
const NOTHING: usize = std::usize::MAX;
const DX: [usize; 4] = [1, 0, std::usize::MAX, 0];
const DY: [usize; 4] = [0, 1, 0, std::usize::MAX];

fn main() {
    let (h, w, d): (usize, usize, usize) = readln();
    let mut a: Vec<(usize, usize)> = vec![(NOTHING, NOTHING); h * w];
    for i in 0..h {
        let xs: Vec<usize> = readln();
        for j in 0..w {
            a[xs[j] - 1] = (i, j);
        }
    }

    let mut dist: Vec<i64> = vec![INF;h*w];

    for i in 0..d {
        dist[i] = 0;
        let mut px = a[i].0;
        let mut py = a[i].1;
        let mut j = i;
        while j + d < h * w {
            let x = a[j + d].0;
            let y = a[j + d].1;
            dist[j + d] = dist[j] + (x as i64 - px as i64).abs() + (y as i64 - py as i64).abs();
            j += d;
            px = x;
            py = y;
        }
    }

    let q: usize = readln();
    let mut res: Vec<i64> = Vec::with_capacity(q);
    for _ in 0..q {
        let (l, r): (usize, usize) = readln();
        res.push(dist[r - 1] - dist[l - 1]);
    }
    let strs: Vec<String> = res.iter().map(|x| x.to_string()).collect();
    println!("{}", strs.join("\n"));
}

trait Read {
    fn read(s: &str) -> Self;
}

fn readln<T: Read>() -> T {
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).unwrap();
    T::read(buf.trim_right())
}

macro_rules! read_impl{
    ($($t:ty)*) => ($(
        impl Read for $t {
            fn read(s: &str) -> $t{
                s.parse().unwrap()
            }
        }
    )*)
}
read_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }

impl Read for String {
    fn read(s: &str) -> Self {
        s.to_string()
    }
}

impl Read for Vec<char> {
    fn read(s: &str) -> Self {
        s.chars().collect()
    }
}

impl<T: Read> Read for Vec<T> {
    fn read(s: &str) -> Self {
        s.split_whitespace().map(T::read).collect()
    }
}

impl<A: Read, B: Read> Read for (A, B) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]))
    }
}

impl<A: Read, B: Read, C: Read> Read for (A, B, C) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]))
    }
}

impl<A: Read, B: Read, C: Read, D: Read> Read for (A, B, C, D) {
    fn read(s: &str) -> Self {
        let tokens: Vec<_> = s.split_whitespace().collect();
        (A::read(tokens[0]), B::read(tokens[1]), C::read(tokens[2]), D::read(tokens[3]))
    }
}


Measured memory_bytes: 13436
#include <stdio.h>
#include <stdlib.h>
#define int long long
#define inf (int)(1e18)

int *x, *a, *s, *skak;

int sum_lt1_r_kak(int l, int r){
	return skak[r] - skak[l];
}

int sum_lt1_r_ak(int l, int r){
	return s[r] - s[l];
}

int x2(int k){
	return k * k;
}

int min(int A, int B){
	return A <= B ? A : B;
}

signed main(){
	int N, X, i, j, ans = inf;
	scanf("%lld%lld", &N, &X);
	x = (int *)malloc(sizeof(int) * (N + 1));
	a = (int *)malloc(sizeof(int) * (N + 1));
	s = (int *)malloc(sizeof(int) * (N + 1));
	skak = (int *)malloc(sizeof(int) * (N + 1));
	x[0] = 0;
	a[0] = 0;
	s[0] = 0;
	skak[0] = 0;
	for(i = 1; i <= N; i++){
		scanf("%lld", &x[i]);
		a[i] = x[i] - x[i - 1];
		s[i] = s[i - 1] + a[i];
		skak[i] = skak[i - 1] + i * a[i];
	}
	int now, stl, str, l, r;
	for(i = 1; i <= N; i++){
		now = (N + i) * X;
		stl = N % i;
		str = N - i;
//		printf("now1 = %lld\n", now);
		for(j = 1; N - j * i > stl; j++){
			l = N - j * i - i;
			r = N - j * i;
			now += i * 1 * sum_lt1_r_ak(l, r);
			now += x2(j + 2) * ((r + 1) * sum_lt1_r_ak(l, r) - sum_lt1_r_kak(l, r));
			now += x2(j + 1) * (sum_lt1_r_kak(l, r) - (l + 1) * sum_lt1_r_ak(l, r));
		}
//		printf("now2 = %lld\n", now);

		l = N - i;
		r = N;
		now += 5 * ((i + l + 1) * sum_lt1_r_ak(l, r) - sum_lt1_r_kak(l, r));
//		printf("now3 = %lld\n", now);
		l = 0;
		r = stl;
//		printf("(l, r, j) = (%lld, %lld, %lld)\n", l, r, j);
		now += i * 1 * sum_lt1_r_ak(l, r);
		now += x2(j + 2) * ((r + 1) * sum_lt1_r_ak(l, r) - sum_lt1_r_kak(l, r));
		now += x2(j + 1) * (sum_lt1_r_kak(l, r) - (l + 1) * sum_lt1_r_ak(l, r) + (i - stl) * sum_lt1_r_ak(0, stl));

		if(now < 0){
			continue;
		}
		ans = min(ans, now);
//		printf("now[%lld] = %lld\n", i, now);
	}
	printf("%lld\n", ans);
	return 0;
}

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

const int MAX = 2000;
const int MOD = 1000000007;

long long fac[MAX], finv[MAX], inv[MAX];

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (int i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(int n, int k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

int main(){
  COMinit();
  int S;
  cin >> S;
  int L = S / 3, N = S % 3;
  ll ans = 0;
  while(L > 0){
    ans = (ans + COM(L-1 + N, N) ) % MOD; //cout<< ans;
    L--;
    N += 3;
  }
  cout << ans;

}


Measured memory_bytes: 3628
/*
 ============================================================================
 Name        : AtCoder_A.c
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

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

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

	if(X<=A+B && X>=A){
		printf("YES");
	}else{
		printf("NO");
	}
	return EXIT_SUCCESS;
}


Measured memory_bytes: 128
// D - Equal Cut

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// const int INF = 2147483647;
const ll INF = 9223372036854775807;
// const ll MOD = 1e9 + 7;

int N;
ll A[200000];
ll cum_A[200001];

ll calc_diff_abs(int l, int m, int r) {
	ll P = cum_A[l];
	ll Q = cum_A[m] - cum_A[l];
	ll R = cum_A[r] - cum_A[m];
	ll S = cum_A[N] - cum_A[r];

	ll max_subseq = max(P, max(Q, max(R, S)));
	ll min_subseq = min(P, min(Q, min(R, S)));

	return max_subseq - min_subseq;
}

int main() {
	cin >> N;

	for (int i=0; i<N; i++) {
		cin >> A[i];
		cum_A[i+1] = cum_A[i] + A[i];
	}

	ll ans = INF;

	for (int m=2; m<=N-1; m++) {
		int l = upper_bound(cum_A, cum_A+m, cum_A[m] / 2) - cum_A;
		int r = upper_bound(cum_A+m, cum_A+N, cum_A[m] + (cum_A[N] - cum_A[m]) / 2) - cum_A;

		ans = min(ans, calc_diff_abs(l, m, r));
		ans = min(ans, calc_diff_abs(l-1, m, r));
		ans = min(ans, calc_diff_abs(l, m, r-1));
		ans = min(ans, calc_diff_abs(l-1, m, r-1));
	}

	cout << ans << endl;

	return 0;
}

Measured memory_bytes: 6720
import java.util.*;
public class Main {
    public static class Pair{
        int pos;
        int state;
        public Pair(int pos,int state){
            this.pos=pos;
            this.state=state;
        }
    }
    public static HashMap<Integer,ArrayList<Pair>>g=new HashMap<>();
    public static int[] x;
    public static boolean[] used;
    public static ArrayList<Integer>ans=new ArrayList<>();

    public static int lower_bound(Pair[] nums, Pair pair) {
        int idx = // Java's binarySearch can be used because no duplicate key exists in this problem.
                Arrays.binarySearch(
                        nums,
                        pair,
                        (a, b) -> a.pos == b.pos ? Integer.compare(a.state, b.state) : Integer.compare(a.pos, b.pos));
        return idx >= 0 ? idx : ~idx;
    }

    public static int upper_bound(Pair[] nums,Pair pair) {
        int l = -1, r = nums.length;
        while (l + 1 < r) { // l:ok, r:ng
            int m = (l + r) / 2;
            // if (mm < bombState) then m is ok.
            if (nums[m].pos == pair.pos
                    ? nums[m].state <= pair.state
                    : nums[m].pos <= pair.pos) {
                l = m;
            } else {
                r = m;
            }
        }
        return r;
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        Pair[] a=new Pair[n];
        x=new int[n+1];
        used=new boolean[n+1];
        for(int i=0;i<n;i++)
        {
           a[i]=new Pair(sc.nextInt(),sc.nextInt());
        }
        Arrays.sort(a, Comparator.comparingInt(c -> c.pos));
        x[0]=a[0].state;
        for(int i=0;i<n-1;i++)
        {
            x[i+1]=a[i].state^a[i+1].state;
        }
        x[n]=a[n-1].state;
        for(int i=0;i<m;i++)
        {
            int l=sc.nextInt();
            int r=sc.nextInt();
            l=lower_bound(a,new Pair(l,0));
            //System.out.println(l);
            r=upper_bound(a,new Pair(r,1));
            //System.out.println(r);
            if(l>r)continue;
            if(g.get(l)==null)g.put(l,new ArrayList<>());
            if(g.get(r)==null)g.put(r,new ArrayList<>());
            g.get(l).add(new Pair(r,i+1));
            g.get(r).add(new Pair(l,i+1));
        }
        for(int i=0;i<n+1;i++)
        {
            if(used[i])continue;

            if(dfs(i)==1){
                System.out.println(-1);
                return;
            }
        }
            System.out.println(ans.size());
            Collections.sort(ans);
            for (int num : ans) {
                System.out.print(num + " ");
            }
            System.out.println("");

    }
    public static int dfs(int v)
    {
        used[v]=true;
        int res=x[v];
        if(g.get(v)==null)return res;
        for(Pair p:g.get(v))
        {
            if(used[p.pos])continue;
            int r=dfs(p.pos);
            if(r==1) ans.add(p.state);
            res^=r;
        }
        return res;
    }
}


Measured memory_bytes: 202448
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <tuple>
#include <cstdio>
#include <bitset>
#include <sstream>
#include <iterator>
#include <numeric>
#include <map>
#include <cstring>

using namespace std;

#define DEBUG_ //!!提出時にコメントアウト!!
#ifdef DEBUG_
	#define dump(x)  cerr << #x << " = " << (x) << endl;
#else
	#define dump(x)  ; //何もしない文
#endif

#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define SZ(x) ((int)(x).size()) //unsignedのサイズをint型に変換
#define pb push_back

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

template <typename T>
std::string printVector(const std::vector<T> &data)
{
    std::stringstream ss;
    std::ostream_iterator<T> out_it(ss, ", ");
    ss << "[";
    std::copy(data.begin(), data.end() - 1, out_it);
    ss << data.back() << "]";
    return ss.str();
}

const int MOD = 1e9+7;
const LL LINF = 1001002003004005006ll;
const int INF = 1001001001;

int d[2][int(1e5)]; // 色
vector<int> v[int(1e5)]; //隣接リスト

void dfs(int x, int y, int z, int w) {
    int i;
    
    d[w][x] = z; // zは距離 wは手番 xは現在地
    
    for (i = 0; i < v[x].size(); i++) {
        if (v[x][i] == y) continue; // 戻るのは許さない
        
        dfs(v[x][i], x, z + 1, w);
    }
}

int main(int argc, char const *argv[])
{
    cin.tie(0);
    ios::sync_with_stdio(false);	
    int n, c1 = 0, c2 = 0, i;
    cin >> n;

    for(i = 0; i < n-1; i++)
    {
        int x,y; cin >> x >> y;
        x--; y--;
        v[x].pb(y);
        v[y].pb(x);
    }

    dfs(0, -1, 0, 0);
    dfs(n - 1, -1, 0, 1);

    for (i = 0; i < n; i++) {
        if (d[0][i] <= d[1][i]) {
            c1++;
        } else {
            c2++;
        }
    }


    if(c1 > c2) cout << "Fennec" << endl;
    else cout << "Snuke" << endl;

}


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

#define ALL(a) begin(a), end(a)
#define SZ(a) ((int)(a).size())
#define REP(i, n) for (int i = 0; i < (n); i++)
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define REPD(i, n) for (int i = (n) - 1; i >= 0; i--)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
#define DEBUG(x) cerr << __PRETTY_FUNCTION__ << ">> " << #x << " : " << x << endl

typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

const int N = 1e5 + 5;

int n;
int root;
int a[N];
bool isLeaf[N];
bool can = true;
vi g[N];

void dfs(int u, int par) {
  ll childrenTotal = 0;
  if (isLeaf[u]) {
    return;
  }
  vi children;
  ll mx = 0;
  for (int v : g[u]) {
    if (v == par) {
      continue;
    }
    dfs(v, u);
    children.push_back(v);
    childrenTotal += a[v];
    mx = max(mx, (ll)a[v]);
  }
  mx = max(mx, 2 * a[u] - childrenTotal);
  if (childrenTotal > 2 * a[u] || mx < 0 || mx > a[u]) {
    can = false;
  }
  a[u] = 2 * a[u] - childrenTotal;
  // if (childrenTotal < a[u] || childrenTotal > 2 * a[u]) {
  //   can = false;
  // } else {
  //   ll cur = childrenTotal - a[u];
  //   a[u] = 2 * a[u] - childrenTotal;
  //   sort(ALL(children), [&] (int x, int y) { return a[x] < a[y]; });
  //   ll largest = 0;
  //   ll limit = cur;
  //   cur *= 2;
  //   for (int c : children) {
  //     if (cur == 0) break;
  //     ll take = min(cur, (ll)a[c]);
  //     largest = max(largest, take);
  //     cur -= take;
  //   }
  //   if (largest > limit || cur > 0) {
  //     can = false;
  //   }
  // }
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  REP(i, n) cin >> a[i];
  if (n == 2) {
    cout << (a[0] == a[1] ? "YES" : "NO") << endl;
    return 0;
  }
  REP(i, n - 1) {
    int u, v;
    cin >> u >> v;
    u--; v--;
    g[u].push_back(v);
    g[v].push_back(u);
  }
  REP(i, n) isLeaf[i] = SZ(g[i]) == 1;
  REP(i, n) {
    if (!isLeaf[i]) {
      root = i;
      dfs(i, -1);
      break;
    }
  }
  if (can && a[root] == 0) {
    cout << "YES" << endl;
  } else {
    cout << "NO" << endl;
  }
  return 0;
}



Measured memory_bytes: 16896
N = gets.to_i
A = {}
sum = 0
line = gets.split(' ').map(&:to_i)

for num in 0..N-1 do
    n = line[num]
    A.store(n, A[n].to_i+1);
    sum += n
end

Q = gets.to_i
q_lines = []
for num in 0..Q-1 do
    line = gets
    q_lines << line.chomp.split(' ').map(&:to_i)
end

for num in 0..Q-1 do
    B = q_lines[num][0].to_i
    C = q_lines[num][1].to_i
    b = A[B].to_i
    A[B] = 0
    sum += b * (C - B) 
    if !A[C]
        A[C] = 0
    end
    A[C] += b
    puts sum
end



Measured memory_bytes: 45508
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <map>
#include <unordered_map>
#include <set>
using namespace std;

typedef long long ll;

#define INF 10e17
#define rep(i,n) for(long long i=0; i<n; i++)
#define repr(i,n,m) for(long long i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<long long>())
#define debug(x) std::cerr << (x) << std::endl;
#define roll(x) for (auto&& itr : x) { debug(itr); }

template <class T> inline void chmax(T &ans, T t) { if (t > ans) ans = t;}
template <class T> inline void chmin(T &ans, T t) { if (t < ans) ans = t;}


// Z algorithm
// 前処理でO(N)で配列lcpを求める。
// S自身とS[i:]とが、先頭から最大で何文字一致しているかをO(1)で求めることができる。
vector<int> Zalgo(const string &S) {
    int N = (int)S.size();
    vector<int> res(N);
    res[0] = N;
    int i = 1, j = 0;
    while (i < N) {
        while (i+j < N && S[j] == S[i+j]) ++j;
        res[i] = j;
        if (j == 0) {++i; continue;}
        int k = 1;
        while (i+k < N && k+res[k] < j) res[i+k] = res[k], ++k;
        i += k, j -= k;
    }
    return res;
}

// ZアルゴリズムとはSとS[i, |S|]の最長接頭辞の長さを記録した配列を作るもの。
// つまり、S[0, 2], S[2, |S|] の共通接頭辞を求めるには、min(2, lcp[2])
// 例えば、この問題では ababa
// Sと, S[2:|S|]のlcpは3、だけどS[0, 1], S[2, |S|] の最大接頭辞は2

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

    int ans = 0;
    for (int i = 0; i < n; ++i) {
        string sub = s.substr(i);
        auto lcps = Zalgo(sub);
        for (int j = 0; j < sub.size(); ++j) {
            // cout << lcps[j] << " " << endl;
            chmax(ans, min(lcps[j], j));
        }
        // END;
    }

    cout << ans << endl;
}


Measured memory_bytes: 256
#include <stdio.h>
#include <inttypes.h>

int Q;
int N[114514];

int count[114514];

int mizukinana;
int fukuennmisato[64][2];
int64_t utiyamayumi;
int64_t yosinagasayuri;

void minaseinori(int idx, int64_t acc) {
	if (idx >= mizukinana) {
		if (acc != utiyamayumi) {
			yosinagasayuri *= acc;
			if (yosinagasayuri > utiyamayumi * 2) yosinagasayuri = utiyamayumi * 2;
		}
	} else {
		int i;
		for (i = 0; i <= fukuennmisato[idx][1]; i++) {
			minaseinori(idx + 1, acc);
			acc *= fukuennmisato[idx][0];
		}
	}
}

int main(void) {
	int max = 0;
	int i;
	if (scanf("%d", &Q) != 1) return 1;
	for (i = 0; i < Q; i++) {
		if (scanf("%d", &N[i]) != 1) return 1;
		if (max < N[i]) max = N[i];
	}
	for (i = 2; i <= max; i++) {
		int tomatu, sumipe = i;
		mizukinana = 0;
		for (tomatu = 2; tomatu * tomatu <= sumipe; tomatu++) {
			if (sumipe % tomatu == 0) {
				int c = 0;
				while (sumipe % tomatu == 0) {
					sumipe /= tomatu;
					c++;
				}
				fukuennmisato[mizukinana][0] = tomatu;
				fukuennmisato[mizukinana][1] = c;
				mizukinana++;
			}
		}
		if (sumipe > 1) {
			fukuennmisato[mizukinana][0] = sumipe;
			fukuennmisato[mizukinana][1] = 1;
			mizukinana++;
		}
		utiyamayumi = i;
		yosinagasayuri = 1;
		minaseinori(0, 1);
		count[i] = count[i - 1] + (yosinagasayuri >= i * 2);
	}
	for (i = 0; i < Q; i++) printf("%d\n", count[N[i]]);
	return 0;
}



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

using namespace std;
using ll = long long;

map <ll, ll> mp1;
map <ll, ll> mp2;

int main() {
    int n; scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        ll Ai; scanf("%lld", &Ai);
        mp1[i + Ai]++, mp2[i - Ai]++;
    }

    ll ans = 0;
    for (auto xx : mp1) {
        ans += (xx.second * mp2[xx.first]);
    }

    // ans /= 2;
    printf("%lld\n", ans);
}

Measured memory_bytes: 37976
file = $stdin
files = file.readlines
file.close

rectCount = 0
diaCount = 0
files.each do | w |
	tmp = w.split(",")
	if (tmp[0].to_i ** 2 + tmp[1].to_i ** 2) == (tmp[2].to_i ** 2) then
		rectCount += 1
	elsif tmp[0].to_i == tmp[1].to_i then
		diaCount += 1
	end
end
puts rectCount
puts diaCount

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

#define WHITE 0
#define GRAY 1
#define BLACK 2

int n,time,head,tail;
int *queue;
int *dist;
int *color;
int **matrix;

void enqueue(int);
int dequeue(void);
void bfs(void);

int main(){
  int i,j,u,k,v;

  scanf("%d",&n);

  queue = malloc(n * sizeof(int));
  color = malloc(n * sizeof(int));
  dist = malloc(n * sizeof(int));

  matrix = malloc(n * sizeof(int *));
  for(i = 0 ; i < n ; i++){
    matrix[i] = malloc(n * sizeof(int));
 }
 for(i = 0 ; i < n ; i++){
   dist[i] = -1;
 }
 for(i = 0 ; i < n ; i++){
   for(j = 0 ; j < n ; j++){
     matrix[i][j] = 0;
   }
 }

 for(i = 0 ; i < n ; i++){
    scanf("%d",&u); u--;
    scanf("%d",&k);
    for(j = 0 ; j < k ; j++){
      scanf("%d",&v); v--;
      matrix[u][v] = 1;
    }
  }

  bfs();
  for(i = 0 ; i < n ; i++){
    printf("%d %d\n",i+1,dist[i]);
  }

  for(i = 0 ; i < n ; i++){
    free(matrix[i]);
  }
  free(matrix);
  free(queue);
  free(dist);
  free(color);
  return 0;
}

void bfs(){
  int u,i;
  for(i = 0 ; i < n ; i++){
    color[i] = WHITE;
  }
  head = tail = 0;
  color[0] = GRAY;
  dist[0] = 0;
  enqueue(0);

  while(head != tail){
    u = dequeue();
    for(i = 0 ; i < n ; i++){
      if(matrix[u][i] == 1 && color[i] == WHITE){
        color[i] = GRAY;
        dist[i] = dist[u] + 1;
        enqueue(i);
      }
    }
    color[u] = BLACK;
  }
}

void enqueue(int q){
  queue[tail++] = q;
}

int dequeue(){
  return queue[head++];
}

Measured memory_bytes: 636
#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#include<stack>
#include<climits>
#include<set>
#include<utility>
#include<typeinfo>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef set<int> S;
#define rep(i, n) for(int i=0; i<n; i++)
const ll MOD=1e9+7;

int main(){

  string s, t, u;
  int a, b;
  cin >> s >> t;
  cin >> a >> b;
  cin >> u;
  if(s==u){
    a--;
  } else {
    b--;
  }
  cout << a << " " << b << endl;

	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define rep(i,n) for (int i=0;i<(n);i++)
using namespace std;
using ll = long long;
using P = pair<int,int>;
 
 
int main() {
    ll N;
    cin >> N;
  int a=N;
    int sum=0;
    while(true){
        sum+=N%10;
        if(N/10==0)break;
        N/=10;
    }
    if(a%sum==0)cout << "Yes" << endl;
    else cout << "No" << endl;

}

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

#define rep(i,n) for (int i = 0; i< (n); ++i)
#define vvec(m,n) vector<vector<int>> (int(m), vector<int>(n))
#define ALL(a) (a).begin(), (a).end()

using ll = long long;

int main(){
    int x, a, b;
    cin >> x >> a >> b;
    if(a >= b)cout << "delicious" << endl;
    else if(a < b && a + x >= b) cout << "safe" << endl;
    else cout << "dangerous" << endl;
}

Measured memory_bytes: 256
right_dic = {(1, 3):5, (1, 5):4, (1, 4):2, (1, 2):3,
             (2, 1):4, (2, 4):6, (2, 6):3, (2, 3):1,
             (3, 1):2, (3, 2):6, (3, 6):5, (3, 5):1,
             (4, 1):5, (4, 5):6, (4, 6):2, (4, 2):1,
             (5, 1):3, (5, 3):6, (5, 6):4, (5, 4):1,
             (6, 2):4, (6, 4):5, (6, 5):3, (6, 3):2}


class Dice:
    def __init__(self, top, front):
        self.top = top
        self.front = front
        self.right = right_dic[(top, front)]
        self.under = 7 - self.top
        self.back= 7 - self.front
        self.left = 7 - self.right

    def spin_right(self):
        self.top, self.right, self.under, self.left = self.left, self.top, self.right, self.under

    def spin_left(self):
        self.top, self.right, self.under, self.left = self.right, self.under, self.left, self.top

    def spin_front(self):
        self.top, self.front, self.under, self.back = self.back, self.top, self.front, self.under

    def spin_back(self):
        self.top, self.front, self.under, self.back = self.front, self.under, self.back, self.top


while True:
    n = int(input())
    if n == 0:
        break

    mp = [[0] * (n * 2 + 2) for _ in range(n * 2 + 2)]
    show = [[0] * (n * 2 + 2) for _ in range(n * 2 + 2)]
    counter = [0] * 7
    STOP, FRONT, RIGHT, BACK, LEFT = 0, 1, 2, 3, 4
    for _ in range(n):
        x, y = n + 1, n + 1
        top, front = map(int, input().split())
        dice = Dice(top, front)
        while True:
            rec = 3
            direct = STOP
            if mp[y + 1][x] < mp[y][x] and dice.front > rec:
                rec = dice.front
                direct = FRONT
            if mp[y][x + 1] < mp[y][x] and dice.right > rec:
                rec = dice.right
                direct = RIGHT
            if mp[y - 1][x] < mp[y][x] and dice.back > rec:
                rec = dice.back
                direct = BACK
            if mp[y][x - 1] < mp[y][x] and dice.left > rec:
                rec = dice.left
                direct = LEFT

            if direct == STOP:
                mp[y][x] += 1
                counter[show[y][x]] -= 1
                counter[dice.top] += 1
                show[y][x] = dice.top
                break
            elif direct == FRONT:
                dice.spin_front()
                y += 1
            elif direct == RIGHT:
                dice.spin_right()
                x += 1
            elif direct == BACK:
                dice.spin_back()
                y -= 1
            elif direct == LEFT:
                dice.spin_left()
                x -= 1

    print(*counter[1:])



Measured memory_bytes: 6592
import std.stdio, std.string, std.conv;
import std.range, std.algorithm, std.array, std.typecons, std.container;
import std.math, std.numeric, core.bitop;

enum inf = 1<<30;

void main() {
    int n, k;
    scan(n, k);
    auto d = readln.split.to!(int[]);
    auto ng = new bool[](10);
    foreach (di ; d) {
        ng[di] = true;
    }

    auto ns = n.to!string;
    auto dp = new int[][](ns.length + 1, 2);
    fillAll(dp, inf);
    dp[0][0] = 0;
    foreach (dig ; 1 .. 10) {
        if (ng[dig]) continue;
        dp[0][1] = min(dp[0][1], dig);
    }

    foreach (i ; 0 .. ns.length) {
        foreach (j ; 0 .. 2) {
            foreach (dig ; (j ? 0 : ns[i] - '0') .. 10) {
                if (ng[dig]) continue;
                if (dp[i][j] == inf) continue;
                dp[i+1][j | (dig > ns[i] - '0')] = min(dp[i+1][j | (dig > ns[i] - '0')], 10*dp[i][j] + dig);
            }
        }
    }

    debug {
        writefln("%(%s\n%)", dp);
    }

    int ans = inf;

    if (dp[ns.length][0] < inf) ans = min(dp[ns.length][0], ans);
    if (dp[ns.length][1] < inf) ans = min(dp[ns.length][1], ans);

    writeln(ans);
}
















































void scan(T...)(ref T args) {
    import std.stdio : readln;
    import std.algorithm : splitter;
    import std.conv : to;
    import std.range.primitives;

    auto line = readln().splitter();
    foreach (ref arg; args) {
        arg = line.front.to!(typeof(arg));
        line.popFront();
    }
    assert(line.empty);
}



void fillAll(R, T)(ref R arr, T value) {
    static if (is(typeof(arr[] = value))) {
        arr[] = value;
    }
    else {
        foreach (ref e; arr) {
            fillAll(e, value);
        }
    }
}


Measured memory_bytes: 256
N = int(input())
L = list(map(int,input().split()))
ans = 0



for i in L:
    for j in L:
        for k in L:
            if i != j and i != k and j != k:
                if i + j > k and i + k > j and j + k > i:
                    if i > j > k:
                        ans += 1
                        
                    
print(ans)

Measured memory_bytes: 9204
#include "bits/stdc++.h"
#define rep(i,n) for(int i=0;i<n;i++)
#define ALL(v) (v).begin(),(v).end()
typedef long long LL;
const int INF = 1 << 25;
const LL MOD = 1000000007LL;
using namespace std;
typedef pair<int, int> P;
LL mod_pow(LL a, LL n) {
	if (n == 0) return 1;
	if (n % 2 == 0) {
		LL x = mod_pow(a, n / 2);
		return (x*x) % MOD;
	}
	else {
		return (a*mod_pow(a, n - 1)) % MOD;
	}
}
LL fact[200001];
LL inv_fact[200001];
LL comb(LL n, LL k) {
	if (n < k) return 0;
	LL ret = fact[n];
	(ret *= inv_fact[k]) %= MOD;
	(ret *= inv_fact[n - k]) %= MOD;
	return ret;
}
int main() {
	fact[0] = inv_fact[0] = 1;
	for (int i = 1; i <= 200000; i++) {
		fact[i] = (fact[i - 1] * i) % MOD;
		inv_fact[i] = (inv_fact[i - 1] * mod_pow(i, MOD - 2)) % MOD;
	}
	int H, W, A, B;
	cin >> H >> W >> A >> B;
	LL ans = 0;
	for (int i = 1; i <= H - A; i++) {
		LL add = (comb((B - 1) + (i - 1), B - 1)*comb((W - B - 1) + (H - i), W - B - 1)) % MOD;
		(ans += add) %= MOD;
	}
	cout << ans << endl;
}

Measured memory_bytes: 3328
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf
import Debug.Trace

readInt = ( readLn :: IO Int )
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = getLine >>= print . uncurry (+) . ( negate . length . filter ( == 'p' ) &&& ( `div` 2 ) . length )

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

static const int MAX = 100;
static const int INF = (1<<21);
int n, m;
int M[MAX][MAX];

int prim(){
    int p[MAX], d[MAX], visit[MAX];

    for(int i = 0; i < n; i++){
        p[i] = -1;
        d[i] = INF;
        visit[i] = 0;
    }

    d[0] = 0;

    while(true){
        int minv = INF;
        int next = -1;
        for(int i = 0; i < n; i++){
            if(minv > d[i] && visit[i] == 0){
                minv = d[i];
                next = i;
            }
        }

        if(next == -1)  break;
        visit[next] = 1;

        for(int i = 0; i < n; i++){
            if(M[next][i] != INF && visit[i] == 0 && d[i] > M[next][i]){
                d[i] = M[next][i];
                p[i] = next;
            }
        }
    }
    
    int sum = 0;
    for(int i = 0; i < n; i++){
        if(p[i] != -1) sum += (M[p[i]][i]/100)-1;
    }

    return sum;
}

int main(){
    while(1){
        scanf("%d\n", &n);
        if(n == 0)  break;

        for(int i = 0; i < MAX; i++){
            for(int j = 0; j < MAX; j++){
                M[i][j] = INF;
            }
        }

        scanf("%d\n" , &m);

        int a, b, d;
        for(int i = 0; i < m; i++){
            scanf("%d,%d,%d\n", &a, &b, &d);
            M[a][b] = M[b][a] = d;
        }

        cout << prim() << endl;
    }

    return 0;
}


Measured memory_bytes: 3244