akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#define rep(i,n) for(int i=0;i<n;i++)
#define ll long long int
#define MAX 1000000007
using namespace std;

struct UnionFind{
	vector<int> par;

	UnionFind(int N) : par(N) { //最初は全てが根であるとして初期化
        for(int i = 0; i < N; i++) par[i] = i;
    }

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

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

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

int main(void){
	int n,m;
	cin >> n >> m;
	vector<int> p(n+1);
	rep(i,n) cin >> p[i+1];

	UnionFind tree(n+1);

	rep(i,m){
		int x,y;
		cin >> x >> y;
		tree.unite(x,y);
	}

	int ans = 0;
	rep(i,n){
		if(tree.same(i+1,p[i+1]))ans++;
	}

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


Measured memory_bytes: 1024
S=input()
T=input()
if len(S)>3 or len(S) < 1 or len(T)>3 or len(T) < 1:
  sys.exit()

a = 0
if S[0] == T[0]:
  a += 1
if S[1] == T[1]:
  a += 1
if S[2] == T[2]:
  a += 1

print(a)

Measured memory_bytes: 3060
#include<iostream>
#include<vector>
#include<array>
using namespace std;

#define rep(i, n) for(int i = 0; i < (int)(n); i++)
using ll = long long;

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

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

const long long INF = 1LL << 60;

const int SIZE = 100010;

array<ll, SIZE> h;
array<ll, SIZE> dp;

ll rec(const int& i) {
    if (dp[i] < INF) {
        return dp[i];
    }

    if (i == 0) return 0;

    ll res = INF;
    chmin(res, rec(i-1) + abs(h[i] - h[i-1]));
    if (i > 1) {
        chmin(res, rec(i-2) + abs(h[i] - h[i-2]));
    }

    return dp[i] = res;
}

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

    rep(i, n) {
        cin >> h[i];
    }

    rep(i, n) {
        dp[i] = INF;
    }

    dp[0] = 0;

    rep(i, n) {
        rep(j, k + 1) {
            chmin(dp[i + j], dp[i] + abs(h[i] - h[i + j]));
        }
    }

    cout << dp[n - 1] << endl;

    return 0;
}

Measured memory_bytes: 1792
import java.util.Scanner;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int D = sc.nextInt();
        int T = sc.nextInt();
        int S = sc.nextInt();
        
        int E = T * S;
        if(E>=D){
            System.out.println("Yes");
        }else{
            System.out.println("No");
        }
    }
}

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

using namespace std;
using ll = long long;
using P = pair<ll, ll>;

ll n, m;
struct City {
    int id = 0, x = 0;
    int pre = 0, year = 0;
    
    string identifical() {
        char s[12];
        sprintf(s, "%06d%06d", pre, x);
        return string(s);
    }
};
vector<City> cities;

void input() {
    cin >> n >> m;
    cities.resize(m);
    int id = 1;
    for(auto &c : cities) {
        c.id = id++;
        cin >> c.pre >> c.year;
    }
}

void solve() {
    sort(cities.begin(), cities.end(), [](City &l, City &r) {
        return l.year < r.year;
    });
    vector<int> ids(n + 1, 0);
    for (auto& c : cities) {
        c.x = ++ids[c.pre];
    }
    sort(cities.begin(), cities.end(), [](City &l, City &r) {
        return l.id < r.id;
    });
    for (auto& c : cities) {
        cout << c.identifical() << endl;
    }
}


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



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

int func(int N) {
  int res = 0;
  while (N) {
    ++res;
    N /= 10;
  }
  return res;
}

int main() {
  int N; cin >> N;
  int res = 0;
  for (int n = 1; n <= N; ++n) if (func(n) & 1) ++res;
  cout << res << endl;}

Measured memory_bytes: 3620
function Main(input) {
  const setting = input.trim().split('\n')
  const x = setting[0].split(' ')[0] - 0
  const arr_length = setting[0].split(' ')[1] - 0

  let ans = 0

  if (arr_length > 0) {
    const num_arr = setting[1].split(' ')
    for (let i = 0; i <= x; i++) {
      let min = x - i
      let answer = num_arr.filter((key) => {
        return parseInt(key) === min
      })
      if (answer.length) {
        let max = x + i
        let answer =num_arr.filter((key) => {
          return parseInt(key) === max
        })
        if (answer.length === 0) {
          console.log(max)
          break
        }
      } else {
        console.log(min)
        break
      }
    }
  } else {
    console.log(x)
  }


  }

Main(require("fs").readFileSync("/dev/stdin", "utf8"));

Measured memory_bytes: 30540
#include<bits/stdc++.h>
#define endl '\n';
#define rep(i,n) for(int i=0; i<(n); i++)
using namespace std;
using ll = long long;
using P = pair<int,int>;
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("Ofast")
constexpr ll INF = 1e18;
constexpr int inf = 1e9;
constexpr double INFD = 1e100;
constexpr ll mod = 1000000007;
constexpr ll mod2 = 998244353;
const double PI = 3.1415926535897932384626433832795028841971;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
// ios::sync_with_stdio(false);
// cin.tie(nullptr);
// ---------------------------------------------------------------------------

int N,MOD;
vector<vector<int>> adj;
vector<vector<ll>> dp;

ll Dfs(const int p, const int v){
    ll res = 1;
    for(int i=0; i<adj[v].size(); i++){
        if(adj[v][i] != p){
            dp[v][i] = Dfs(v,adj[v][i]);
            res *= dp[v][i]+1;
            res %= MOD;
        }
    }
    return res;
}

void Rev(const int p, const int v, const ll add){
    for(int i=0; i<adj[v].size(); i++){
        if(adj[v][i] == p){
            dp[v][i] = add;
            break;
        }
    }
    const int deg = adj[v].size();
    vector<ll> l(deg), r(deg);
    for(int i=0; i<deg; i++) r[i] = ((l[i] = (dp[v][i]+1)) %= MOD);
    for(int i=1; i<deg; i++) (l[i] *= l[i-1]) %= MOD;
    for(int i=deg-2; i>=0; i--) (r[i] *= r[i+1]) %= MOD;

    for(int i=0; i<deg; i++){
        if(adj[v][i] != p){
            ll add_c = 1;
            if(i != 0) (add_c *= l[i-1]) %= MOD;
            if(i != deg-1) (add_c *= r[i+1]) %= MOD;
            Rev(v, adj[v][i],add_c);
        }
    }
}

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> N >> MOD;
    adj.resize(N);
    for(int i=0; i<N-1; i++){
        int x,y;
        cin >> x >> y;
        adj[x-1].push_back(y-1);
        adj[y-1].push_back(x-1);
    }
    dp.resize(N);
    for(int v=0; v<N; v++) dp[v].resize(adj[v].size());

    Dfs(-1,0);
    Rev(-1,0,0);

    for(int v=0; v<N; v++){
        ll ans = 1;
        for(ll add : dp[v]) (ans *= (add+1)) %= MOD;
        cout << ans << endl;
    }

    return 0;
}

Measured memory_bytes: 27904
#include <iostream>
using namespace std;
int main()
{
	int n, i, j, k, m, c = 0, a[100] = {};
	cin >> n;
	for(i = 0; i < n; ++i)
		cin >> a[i];
	
	for(i = 0; i < n; ++i){
		m = i;
		for(j = i; j < n; ++j){
			if( a[j] < a[m] )
				m = j;
		}
		if( m != i ){
			k = a[i];
			a[i] = a[m];
			a[m] = k;
			++c;
		}
	}

	for(i = 0; i < n; ++i){
		cout << a[i];
		if( i != n - 1 )
			cout << " ";
	}
	cout << "\n" << c << "\n";

	return 0;
}

Measured memory_bytes: 1164
import java.util.*;

public class Main{
	String name = "CYRMGB";
	
	//サイコロ	//dice is, 2 = south, 3 = east, 1 = top, 6 = bottom, 4 = west, 5 = north;
	class Dice{
		int [] dice;
		public Dice(int[] dice) {
			this.dice = dice;
		}
		private void slide() {
			swap(2,4,5,3);
		}
		private void turn(char c) {
			switch(c){
			case 'n': swap(1,5,6,2); break;
			case 's': swap(1,2,6,5); break;
			case 'w': swap(1,4,6,3); break;
			case 'e': swap(1,3,6,4); break;
			}
		}
		private void swap(int i, int j, int k, int l) {
			int temp = dice[l];
			dice[l] = dice[k];
			dice[k] = dice[j];
			dice[j] = dice[i];
			dice[i] = temp;
		}
	}
	
	private void doit(){
		Scanner sc = new Scanner(System.in);
		while(true){
			int n = sc.nextInt();
			if(n == 0) break;
			Dice [] d = new Dice[n];
			for(int i = 0; i < n; i++){
				int [] tempdice = new int[7];
				for(int j = 1; j <= 6; j++){
					String s = sc.next().charAt(0) + "";
					tempdice[j] = name.indexOf(s);
				}
				d[i] = new Dice(tempdice);
			}
			
			int count = 0;
			for(int i = 0; i < n; i++){
				for(int j = i + 1; j < n; j++){
					if(isSame(d[i], d[j])){
						count++;
						break;
					}
				}
			}
			System.out.println(count);
		}
	}
	
	private boolean isSame(Dice aa, Dice bb) {
		String [] order = {"", "n", "s", "w", "e", "nn"};
		String [] revorder = {"", "s", "n", "e", "w", "nn"};
		Dice a = new Dice(aa.dice);
		Dice b = new Dice(bb.dice);
		for(int i = 0; i < order.length ; i++){
			
			for(int j = 0; j < order[i].length(); j++){
				char c = order[i].charAt(j);
				b.turn(c);
			}
			
			for(int j = 0; j < 4; j++){
				b.slide();
				boolean res = comp(a, b);
				if(res){
					return true;
				}
			}
			
			for(int j = 0; j < revorder[i].length(); j++){
				char c = revorder[i].charAt(j);
				b.turn(c);
			}
		}
		return false;
	}

	private boolean comp(Dice a, Dice b) {
		for(int i = 1; i <= 6; i++){
			if(a.dice[i] != b.dice[i]) return false;
		}
		return true;
	}

	private void debug(Object... o) { System.out.println("debug = " + Arrays.deepToString(o)); }

	public static void main(String[] args) {
		new Main().doit();
	}
}

Measured memory_bytes: 27768
#include <iostream>
#include <vector>
#include <complex>
#include <cstdlib>
#include <iomanip>

using namespace std;

const double eps = 1e-10;
typedef complex<double> Point;

inline double cross(const Point& a, const Point& b){
    return imag(conj(a) * b);
}

inline double dot(const Point& a, const Point& b){
    return real(conj(a) * b);
}

int ccw(Point a, Point b, Point c){
    b -= a; c -= a;
    if(cross(b, c) > eps) return  1;
    if(cross(b, c) < -eps)return -1;
    if(dot(b, c) < 0)     return  2;
    if(norm(b) < norm(c)) return -2;
    return 0;
}

struct Line : vector<Point> {
    Line(const Point& a, const Point& b):vector<Point>{a, b}{}
};

inline bool interSP(const Line& s, const Point& p){
    return abs(s[0] - p) + abs(s[1] - p) - abs(s[1] - s[0]) < eps;
}

inline bool interSS(const Line& s, const Line& t){
    return ccw(s[0], s[1], t[0]) * ccw(s[0], s[1], t[1]) <= 0 &&
           ccw(t[0], t[1], s[0]) * ccw(t[0], t[1], s[1]) <= 0;
}

inline Point proj(const Line& l, const Point& p){
    double t = dot(p - l[0], l[1] - l[0]) / norm(l[1] - l[0]);
    return l[0] + (l[1] - l[0]) * t;
}

inline double distSP(const Line& s, const Point& p){
    const Point r = proj(s, p);
    return interSP(s, r)? abs(r - p): min(abs(s[0] - p), abs(s[1] - p));
}

inline double distSS(const Line& s, const Line& t){
    return interSS(s, t)? 0: min(min(distSP(s, t[0]), distSP(s, t[1])),
                                 min(distSP(t, s[0]), distSP(t, s[1])));
}

int main(){
    int q;
    cin >> q;
    while(q--){
        int x0, y0, x1, y1, x2, y2, x3, y3;
        cin >> x0 >> y0 >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
        Line s(Point(x0, y0), Point(x1, y1)), t(Point(x2, y2), Point(x3, y3));
        cout << fixed << setprecision(10) << distSS(s, t) << '\n';
    }
    return 0;
}

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

#define REP(i, x, n) for (int i = x; i < (int)(n); i++)
#define rep(i, n) REP(i, 0, n)
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define sz(x) (int)(x.size())
#define popcount(x) __builtin_popcount(x)
#define popcountll(x) __builtin_popcountll(x)
#define uniq(x) x.erase(unique(x.begin(), x.end()), x.end())
#define F first
#define S second
#define mp make_pair
#define eb emplace_back
#define pii pair<int, int>
#define pll pair<ll, ll>

using namespace std;

typedef long long ll;

/* --- INFの値が適切か確認する --- */
// const int INF = 1 << 30;
// const ll INF = 1LL << 60;
// const int MOD = 1000000007;

int main() {
  int a, b, c;
  cin >> a >> b >> c;
  cout << max(0, b + c - a) << endl;
}


Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ABC118C
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                Console.SetIn(new StreamReader(args[0]));
            }

            new Program().calc();
        }

        void calc()
        {
            var n = int.Parse(Console.ReadLine());
            var hpList = Console.ReadLine().Split(' ').ToList().ConvertAll(int.Parse);
            Console.WriteLine(attack(hpList));

        }

        int attack(List<int> hpList)
        {
            // hpList.ForEach(hp => Console.Write(hp + ","));
            // Console.WriteLine();

            var min = hpList.Min();
            hpList = hpList.ConvertAll(hp => {
                if (hp % min == 0)
                {
                    return min;
                }
                else
                {
                    return hp % min;
                }
            });

            if (hpList.Min() == hpList.Max())
            {
                return min;
            }
            else
            {
                return attack(hpList);
            }
        }
    }
}


Measured memory_bytes: 20192
use proconio::input;
use proconio::marker::Usize1;

fn scoring(_d: usize, c: &Vec<i64>, s: &Vec<Vec<i64>>, t: &Vec<usize>) -> i64 {
    let mut last = vec![0; 26];
    let mut score = 0;
    for (i, &t_i) in t.iter().enumerate() {
        let d_i = i as i64 + 1;
        last[t_i] = d_i;
        score += s[i][t_i];
        for i in 0..26 {
            score -= c[i] * (d_i - last[i]);
        }
    }
    score
}

fn main() {
    input! {
        d: usize,
        c: [i64; 26],
        s: [[i64; 26]; d],
        mut t: [Usize1; d],
        m: usize,
        dq: [(Usize1, Usize1); m],
    };
    // let a = score(d, &c, &s, &t);
    for &(d_i, q_i) in dq.iter() {
        // let old = t[d_i];
        t[d_i] = q_i;
        let a_new = scoring(d, &c, &s, &t);
        // if a_new <= a {
        //     t[d_i] = old;
        // }
        println!("{}", a_new);
    }
}


Measured memory_bytes: 4336
import numpy as np

N = int(input())
As = input().split()

for i in range(N):
  As[i] = int(As[i])
  
As = np.array(As)

flag = True
counter = 0
while flag:
  div = np.where(As%2==0,0,1)
  if div.sum()>0:
    flag = False
  else:
    As = As//2
    counter += 1
print(counter)

Measured memory_bytes: 12504
s = input()
s1 = s[0]
s2 = s[2:-1]
s = s.replace('A','')
s = s.replace('C','')
t = s.lower()
if(s1 == 'A' and s2.count('C') == 1 and t == s):
    print('AC')
else:
    print('WA')

Measured memory_bytes: 3064
def binary_search(arr,key)
  l = 0; r = arr.size-1
  while true
    if l >= r
      if arr[r] > key
        return r-1
      else
        return r
      end
    end
    mid = (l+r)/2
    return mid if key == arr[mid]
    if key < arr[mid]
      r = mid - 1
    else
      l = mid + 1
    end
  end
end


N, M, K = gets.split(" ").map(&:to_i)
a = []; b = []
a = gets.split(" ").map(&:to_i)
b = gets.split(" ").map(&:to_i)
sumsa = [0]; sumsb = [0]
max = 0; cnt = 0
a.each do |val|
  sumsa.push(sumsa.last + val)
end
b.each do |val|
  sumsb.push(sumsb.last + val)
end

sumsa.each_with_index do |suma, i|
  break if suma > K
  cnt = i
  rest = K - suma
  cnt += binary_search(sumsb, rest)
  max = [max, cnt].max
end
  
puts max

Measured memory_bytes: 45084
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>

using namespace std;
typedef long long ll;

int main(){
  int x;cin>>x;
  int a,b;
  if(x==1){
    cout<<"Hello World"<<endl;
  }else{
    cin>>a>>b;
    cout<<a+b<<endl;
  }

}

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

#define ll long long
#define mod 1000000007
#define ffor(i,a,b) for(int i=a;i<b;i++)
#define bfor(i,a,b) for(int i=a-1;i>=b;i--)
#define mp make_pair
#define pb push_back
#define ff first
#define ss second
#define mem(x,y) memset(x,y,sizeof(x))
#define all(x) x.begin(),x.end()
#define SP(x) setprecision(x)
#define sz(x) (int)x.size()
#define fast  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define PI 3.14159265358979323846
#define lb lower_bound
#define ub upper_bound
#define bs binary_search
#define endl '\n'

int main()
{
    

    int n;
    cin>>n;
    map<ll,ll> m;

    ll sum=0;
    ffor(i,0,n)
    {
        int x;
        cin>>x;
        m[x]++;
        sum+=x;
    }
    int q;
    cin>>q;
    while(q--)
    {
        int a,b;
        cin>>a>>b;
        sum-=a*m[a];
        sum+=b*m[a];
        m[b]+=m[a];
        m[a]=0;
        cout<<sum<<endl;
    }
    
    return 0;
}



Measured memory_bytes: 9404
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

type contest struct {
	in  io.Reader
	out io.Writer
}

func (con *contest) scan(a ...interface{}) (int, error) {
	return fmt.Fscan(con.in, a...)
}
func (con *contest) scanln(a ...interface{}) (int, error) {
	return fmt.Fscanln(con.in, a...)
}
func (con *contest) scanf(f string, a ...interface{}) (int, error) {
	return fmt.Fscanf(con.in, f, a...)
}
func (con *contest) print(a ...interface{}) (int, error) {
	return fmt.Fprint(con.out, a...)
}
func (con *contest) println(a ...interface{}) (int, error) {
	return fmt.Fprintln(con.out, a...)
}
func (con *contest) printf(f string, a ...interface{}) (int, error) {
	return fmt.Fprintf(con.out, f, a...)
}
func main() {
	in := bufio.NewReader(os.Stdin)
	out := bufio.NewWriter(os.Stdout)
	defer out.Flush()
	con := &contest{in: in, out: out}
	con.main()
}

func (con *contest) main() error {
	a := 0
	m := map[int]bool{}
	con.scan(&a)
	m[a] = true
	con.scan(&a)
	m[a] = true
	con.scan(&a)
	m[a] = true
	con.println(len(m))
	return nil
}


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

using namespace std;

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

	for(int i = 9;i > 0;i--){
		if(a % i == 0){
			a = a/i;
			break;
		}
		if(a == 1){
			a = 20;
		}
	}
	if(a < 10){
		cout << "Yes" << endl;
	}
	else{
		cout << "No" << endl;
	}
}



Measured memory_bytes: 256
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
    return list(map(int,input().split()))
def m(): #複数文字
    return map(int,input().split())
def onem(): #Nとかの取得
    return int(input())
def s(x): #圧縮
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): #listをスペースごとに分ける
    return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
    return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False
"""
def nibu(x,n,r):
    ll = 0
    rr = r
    while True:
        mid = (ll+rr)//2

    if rr == mid:
        return ll
    if (ここに評価入れる):
        rr = mid
    else:
        ll = mid+1
"""

import heapq

def dijkstra():
    #n:辺数,w:スタート一
    n,w = map(int,input().split())

    edge = [[] for i in range(n)]
    dg = 10**7
    # edge[i]:[コスト]
    for i in range(n-1):
        x,y = map(int,input().split())
        z = 1
        x -= 1
        y -= 1
        edge[x].append(dg + y)
        edge[y].append(dg + x)
    
    s = w-1
    d = [-1]*n
    d[s] = 0

    edgelist = []
    for e in edge[s]:
        heapq.heappush(edgelist,e)

        

    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        v,c = minedge%dg,minedge//dg
        if d[v] >= 0:
            continue
        d[v] = c
        for e in edge[v]:
            vNext = e%dg
            if d[vNext]:
                heapq.heappush(edgelist, (e//dg+d[v])*dg + vNext)

    return d


def warshall_floyd(n,d):
    for k in range(n):
        for i in range(n):
            for j in range(n):
                d[i][j] = min(d[i][j],d[i][k] + d[k][j])
    return d

mod = 10**9+7 #出力の制限
N = 10**5
def cmb(n, r):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod
def p(n,r):
    if ( r<0 or r>n ):
        return 0
    return g1[n] * g2[n-r] % mod

g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル

for i in range( 2, N + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )
# a = cmb(n,r)


N,M = m()


a = l()

a.sort()

po = cmb(N,M)

aa = s(a)

cc = 0

count = 0
for i in range(len(aa)):
    cc += aa[i][1]
    count += (cmb(cc,M) - cmb(cc-aa[i][1],M))*aa[i][0]
    count -= (cmb(N-cc+aa[i][1],M) - cmb(N-cc,M))*aa[i][0]
    count %= mod
print(count)

























Measured memory_bytes: 70644
#include <bits/stdc++.h>
 
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define li long long
#define itn int
 
using namespace std;
 
inline int nxt(){
	int n;
	scanf("%d", &n);
	return n;
}

template <typename T>
ostream& operator <<(ostream& ostr, const vector<T>& a) {
	ostr << "(";
	for (size_t i = 0; i < a.size(); ++i) {
		if (i) {
			ostr << ", ";
		}
		ostr << a[i];
	}
	ostr << ")";
	return ostr;
}

int main() {
	int n = nxt();
	multiset<int> S;
	for (int i = 0; i < n; ++i) {
		S.insert(nxt());
	}

	n = nxt();
	for (int i = 0; i < n; ++i) {
		int x = nxt();
		auto it = S.find(x);
		if (it == S.end()) {
			puts("NO");
			return 0;
		} else {
			S.erase(it);
		}
	}

	puts("YES");

	return 0;
}

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

int main() {
  int a, b;
  cin >> a >> b;
  int mina = ceil(a * 12.5);
  int maxa = floor((a + 1) * 12.5);
  if (a % 2 == 1) {
    maxa -= 1;
  }
  int minb = b * 10;
  int maxb = b * 10 + 9;
  if (mina > maxb || minb > maxa) {
    cout << -1 << endl;
  } else {
    cout << max(mina, minb) << endl;
  }
  return 0;
}


Measured memory_bytes: 256
#0:中央 1:南 2:東 3:西 4:北 5:裏側
class Dice():
    def __init__(self):
        self.number = [i for i in range(6)]
        self.work = [i for i in range(6)]

    def setNumber(self,n0,n1,n2,n3,n4,n5):
        self.number[0] = n0
        self.number[1] = n1
        self.number[2] = n2
        self.number[3] = n3
        self.number[4] = n4
        self.number[5] = n5

    def roll(self,loc):
        for i in range(6):
            self.work[i] = self.number[i]

        if loc == "E":
            self.setNumber(self.work[3],self.work[1],self.work[0],self.work[5],self.work[4],self.work[2])
        elif loc == "N":
            self.setNumber(self.work[1],self.work[5],self.work[2],self.work[3],self.work[0],self.work[4])
        elif loc == "S":
            self.setNumber(self.work[4],self.work[0],self.work[2],self.work[3],self.work[5],self.work[1])
        elif loc == "W":
            self.setNumber(self.work[2],self.work[1],self.work[5],self.work[0],self.work[4],self.work[3])

    def get_Top(self):
        return self.number[0]

dice = Dice()
table = list(map(int,input().split()))
dice.setNumber(table[0],table[1],table[2],table[3],table[4],table[5])

loc_array = input()
 
for tmp_loc in loc_array:
    dice.roll(tmp_loc)

print(dice.get_Top())


Measured memory_bytes: 5616
#include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rrep(i, n) for(int i = 1; i <= (int)(n); i++)
#define drep(i, n) for(int i = (n)-1; i >= 0; i--)
#define ALL(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
const ll LINF = 1001002003004005006ll;
const int INF = 1001001001;

// Mod int
const int mod = 1000000007;
// const int mod = 998244353;
struct mint {
  ll x;
  mint():x(0){}
  mint(ll x):x((x%mod+mod)%mod){}
  // mint(ll x):x(x){}
  mint& fix() { x = (x%mod+mod)%mod; return *this;}
  mint operator-() const { return mint(0) - *this;}
  mint& operator+=(const mint& a){ if((x+=a.x)>=mod) x-=mod; return *this;}
  mint& operator-=(const mint& a){ if((x+=mod-a.x)>=mod) x-=mod; return *this;}
  mint& operator*=(const mint& a){ (x*=a.x)%=mod; return *this;}
  mint operator+(const mint& a)const{ return mint(*this) += a;}
  mint operator-(const mint& a)const{ return mint(*this) -= a;}
  mint operator*(const mint& a)const{ return mint(*this) *= a;}
  bool operator<(const mint& a)const{ return x < a.x;}
  bool operator==(const mint& a)const{ return x == a.x;}
};
istream& operator>>(istream&i,mint&a){i>>a.x;return i;}
ostream& operator<<(ostream&o,const mint&a){o<<a.x;return o;}
//



int main() {
  int n, d;
  cin >> n >> d;
  vector<ll> x(n), y(n);
  rep(i, n) cin >> x[i] >> y[i];
  int c = 0;
  ll d2 = (ll)d*d;
  rep(i, n) {
    ll dist2 = x[i]*x[i] + y[i]*y[i];
    if (dist2 <= d2) c++;
  }
  cout << c << endl;
}

Measured memory_bytes: 6392
#include<bits/stdc++.h>
using namespace std; 
#define ll long long
#define rep(i,x,y)  for(ll i=x;i<y;++i)
#define For(i,x,y)  for(ll i=x;i<=y;++i) 
#define FOr(i,x,y)  for(ll i=x;i>=y;--i) 
#define pi acos(-1)
#define mk make_pair<ll,ll>
#define pa pair<ll,ll>
#define lf else if
#define max(x,y)    ((x)<(y)?(y):(x))
#define min(x,y)    ((x)<(y)?(x):(y))
#define sqr(x)		(x)*(x)
#define abs(x)		(x)>0?(x):-(x)
#define Mul(x,y)    x=x*(y)%mod
#define Add(x,y)    x=(x+(y))%mod
#define Max(x,y)	x=x<(y)?(y):x
#define Min(x,y)	x=x>(y)?(y):x
#define E(x) 		return writeln(x),0
#define p(x)		printf("~%d~\n",x)
#define pp(x,y)		printf("~~%d %d~~\n",x,y)
#define ppp(x,y,z)	printf("~~~%d %d %d~~~\n",x,y,z)
#define f_in(x)		freopen(x".in","r",stdin)
#define f_out(x) 	freopen(x".out","w",stdout)
#define open(x)		f_in(x),f_out(x)
#define fi first
#define se second
typedef complex<double> E;
namespace SHENZHEBEI{
#ifdef LOCAL
    struct _{_(){freopen("cf.in","r",stdin);}}_;
#endif 
#define NEG 0
    const int L=2333333;
    char SZB[L],*S=SZB,*T=SZB;
    inline char gc(){   if (S==T){  T=(S=SZB)+fread(SZB,1,L,stdin); if (S==T) return '\n';  }   return *S++;    }
#if NEG
    inline ll read(){    ll x=0,f=1; char ch=gc();   for (;!isdigit(ch);ch=gc()) if (ch=='-') f=-1;  for (;isdigit(ch);ch=gc())  x=x*10-48+ch;   return x*f; }
    inline void write(ll x){    if (x<0) putchar('-'),x=-x;  if (x>=10)   write(x/10);    putchar(x%10+'0');  }
#else
    inline ll read(){    ll x=0; char ch=gc();   for (;!isdigit(ch);ch=gc());    for (;isdigit(ch);ch=gc())  x=x*10-48+ch;   return x;   }
    inline void write(ll x){    if (x>=10)   write(x/10);    putchar(x%10+'0');  }
#endif
    inline char readchar(){ char ch=gc();   for(;isspace(ch);ch=gc());  return ch;  }
    inline ll readstr(char *s){ char ch=gc();   int cur=0;  for(;isspace(ch);ch=gc());      for(;!isspace(ch);ch=gc())  s[cur++]=ch;    s[cur]='\0';    return cur; }
    inline void writeln(ll x){  write(x);   puts("");   }
}using namespace SHENZHEBEI;
const ll N=120000;
ll n,a[N];
bitset<2010*2010>f;
int main(){
	f[0]=1;
	n=read(); 
	For(i,1,n){
		ll x=read();	f|=f<<x;
	}
	ll x=f.count()/2+1;
	For(i,0,100000000)	if (f[i]){
		if (!--x)	return writeln(i),0;
	}
}

Measured memory_bytes: 1792
import kotlin.math.*

fun str() = readLine()!!
fun int() = str().toInt()
fun long() = str().toLong()

fun read(d:String = " ") = str().split(d)
fun <T> list(d:String = " ",f:String.()->T) = read(d).map {f(it)}
fun list() = list {toInt()}.toIntArray()

fun <T> T.print() = println(this)

fun main() {
	abc000X()
}

fun abc000X() {
	val (x,n)=list()
	if(n==0){
		println(x)
		return
	}

	val p=list().toHashSet()

	println((0..101).filterNot(p::contains).minBy {abs(it-x)*1000+it})
}


Measured memory_bytes: 40496
#include <bits/stdc++.h>
#define FI first
#define SE second
#define EPS 1e-9
#define ALL(a) a.begin(),a.end()
#define SZ(a) int((a).size())
#define MS(s, n) memset(s, n, sizeof(s))
#define FOR(i,a,b) for (int i = (a); i <= (b); i++)
#define FORE(i,a,b) for (int i = (a); i >= (b); i--)
#define FORALL(it, a) for (__typeof((a).begin()) it = (a).begin(); it != (a).end(); it++)
#define WHATIS(x) cout << #x << " is " << x << endl;
#define ERROR(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); err(_it, args); }
//__builtin_ffs(x) return 1 + index of least significant 1-bit of x
//__builtin_clz(x) return number of leading zeros of x
//__builtin_ctz(x) return number of trailing zeros of x

using namespace std;
using ll = long long;
using ld = double;
typedef pair<int, int> II;
typedef pair<ll, II> III;
typedef complex<ld> cd;
typedef vector<cd> vcd;

void err(istream_iterator<string> it) {}
template<typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
    cout << *it << " = " << a << endl;
    err(++it, args...);
}

const ll MODBASE = 1000000007LL;
const int MAXN = 100010;
const int MAXM = 100010;
const int MAXK = 510;
const int MAXQ = 200010;

int n, k, a[MAXN];

int main() {
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cin >> n >> k;
    FOR(i,1,n) cin >> a[i];
    sort(a+1, a+n+1);
    int res = 1000000000;
    FOR(i,1,n) {
        int r = i + k - 1;
        if (r > n) break;
        res = min(res, a[r] - a[i]);
    }
    cout << res;
    return 0;
}

Measured memory_bytes: 640
#include<bits/stdc++.h>
using namespace std;
using ll = int64_t;
int main(){
	ll k, a, b; cin >> k >> a >> b;
	ll po = k - a;
	if(po <= 0){
		cout << 1 << endl;
	}else if(b - a >= 0){
		cout << -1 << endl;
	}else{
		ll yo = po / (a - b) + (po % (a - b) != 0);
		cout << yo * 2 + 1 << endl;
	}
	return 0;
}

Measured memory_bytes: 256
# from time import perf_counter


def main():
    r, g, b, n = list(map(int, input().split()))
    count = 0
    x1, x2, x3 = sorted([r, g, b], reverse=True)
    # print(x1, x2, x3)
    for i in range(n // x1 + 1):
        for j in range((n - i) // x2 + 1):
            rest = n - (x1 * i) - (x2 * j)
            # print(f'{x1}*{i} + {x2}*{j} = {n - rest}')
            if rest == 0:
                # print(f'{x1}*{i} + {x2}*{j} + {x3}*0 = {n}')
                count += 1
            else:
                # print(f'{x1}*{i} + {x2}*{j} + {x3}*? = {n}')
                count += (1 if rest > 0 and rest % x3 == 0 else 0)
            # for k in range((n - i - j) // x3 + 1):
                # print(f'{r}*{i} + {g}*{j} + {b}*{k} = {r*i+g*j+k+b*k}')
            #    if x1 * i + x2 * j + x3 * k == n:
            #        count += 1

    print(count)


if __name__ == '__main__':
    # s = perf_counter()
    main()
    # e = perf_counter()
    # print('process:', e - s)


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

vector<tuple<string, int, int>> r;

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string s;
		int p;
		cin >> s >> p;
		r.emplace_back(s, 100 - p, i);
	}
	sort(r.begin(), r.end());
	for (int i = 0; i < n; i++) {
		cout << get<2>(r[i]) + 1 << endl;
	}
}


Measured memory_bytes: 256
#include <iostream>
using namespace std;
int main()
{
	int x, a, b;
	cin >> x >> a >> b;
	if(x + a < b){
		cout << "dangerous" << endl;
	}else{
		if(a<b){
			cout << "safe" << endl;
		}else{
			cout << "delicious" << endl;
		}
	}
	

	return 0;
}


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

using namespace std;
typedef long long ll;

int main(void){
long double a,b,c;
cin >> a >> b >> c;

long double eps = 1.0E-14;

if(sqrt(a) + sqrt(b) + eps < sqrt(c)){
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}

return 0;
}


Measured memory_bytes: 256
//#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<cmath>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<cstdlib>
#include<bitset>
#include<sstream>
#include<queue>
#include<stack>
#include<list>
#include<limits>
#include<iomanip>

using namespace std;

typedef long long int ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int,int> pt;
typedef pair<ll,ll> pll;

#define Max 1000001
#define intinf 2147483647
#define longlonginf 9223372036854775807
#define MOD 998244353
#define MOD2 1000000007
#define fastio ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
#define vint vector<int>
#define vll vector<long long>
#define endl '\n'
#define fi first
#define se second
#define pb push_back
#define F(i,n) for(int i = 0;i<n;i++)
#define Fr(i,l,r) for(int i = l;i <= r;i++)
#define rF(i,n) for(int i = n-1;i>=0;i--)


//#define min(a,b) a>b?b:a
//#define max(a,b) a>b?a:b
#define all(arr) arr.begin(),arr.end()
//#define sort(vec) sort(vec.begin(),vec.end())
//#define reverse(vec) reverse(vec.begin(),vec.end())


ll Lpow(ll a,ll b)
{
    ll ans = 1;
    while(b > 0)
    {
        if(b%2)
            ans = (ans*a);
        a = (a*a);
        b = b/2;
    }
    return ans;
}

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


signed main()
{
    fastio;
    
    int n,k;
    cin >> n >> k;
    
    vector<int> arr(n);
    
    F(i,n)
    cin >> arr[i];
    
    vector<int> cost(n,intinf);
    
    cost[0] = 0;
    
    for(int i = 1;i<n;i++)
    {
        int cnt = 0;
        for(int j = i-1;j>=0 && cnt < k;j--,cnt++)
        {
            cost[i] = min(cost[i],cost[j] + abs(arr[i] - arr[j]));
        }
    }
    
    cout << cost[n-1] << endl;
    
    return 0;
}


Measured memory_bytes: 1024
// Problem : C - Average Length
// Contest : AtCoder - AtCoder Beginner Contest 145
// URL : https://atcoder.jp/contests/abc145/tasks/abc145_c
// Memory Limit : 1024 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include<bits/stdc++.h>
#include<set>
#include<map>
#include<bitset>
#define rep(i,a,b)  for(i=a;i<b;i++)
#define Sort(a)	sort(a.begin(),a.end())
#define rev(a)	reverse(a.begin(),a.end())
#define all(a)	(a).begin(),(a).end()
#define vll vector<long long int>
#define lli long long int
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define db long double
#define M 1000000007
#define pi 3.1415926535897932384626433832795028841971
#define INF 1e18

#define MAX 200005

using namespace std;
lli min(lli a,lli b){return a<b?a:b;}
lli min(lli a,lli b,lli c){a=min(a,b);a=min(a,c);return a;}
lli max(lli a,lli b){return a>b?a:b;}
lli max(lli a,lli b,lli c){a=max(a,b);a=max(a,c);return a;}
lli dsum(lli n){lli ans=0;while(n){ans+=(n%10);n/=10;}return ans;}
lli power(lli a,lli b){lli res=1;while(b){if(b&1) res=res*a;a=a*a;b>>=1;}return res;}
lli power(lli a,lli b,lli m){if(b==0)	return 1;if(b==1)	return a%m;lli res=1;a=a%m;while(b){if(b&1){res=(res*a)%m;}a=((a%m)*(a%m))%m;b>>=1;}return res;}
lli Ceil(lli a,lli b){lli res=a/b;if(a%b!=0)	res++;return res;}

template<typename T>istream &operator>>(istream &is, vector<T> &v) { for (T &t : v) is >> t; return is; }
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v) { for (const T &t : v) {os << t <<" ";} os << '\n'; return os; }

lli dxx[]={1,1,0,-1,-1,-1,0,1};
lli dyy[]={0,1,1,1,0,-1,-1,-1};
lli dx[]={1,0,-1,0};
lli dy[]={0,1,0,-1};

struct pll{
	lli x,y;
};
bool comp(pll a,pll b){
	if(a.x==b.x)	return a.y<b.y;
	else	return a.x<b.x;
}
void solve(lli the)
{
	char ch;
	db aa,bb,cc,dd,xx;
	string s1,s2,s3,str;
    lli i,j,k,a,b,c,d,n,m,l,r,x,y,z,low,high,mid,sum=0,ans=0,temp,t;
    cin >> n;
    pair<db,db>pa[n+1];
    rep(i,1,n+1){
    	cin >> pa[i].first >> pa[i].second;
    }
    sum=1;
    for(i=1;i<=n;i++){
    	sum*=i;
    }
    dd=sum;
    sum*=(n-1);
    a=n*(n-1);a/=2;sum/=a;
    bb=0.0;xx=sum;
    for(i=1;i<=n;i++){
    	for(j=i+1;j<=n;j++){
    		cc=0;
    		cc+=(pa[i].first-pa[j].first)*(pa[i].first-pa[j].first);
    		cc+=(pa[i].second-pa[j].second)*(pa[i].second-pa[j].second);
    		cc=sqrt(cc);
    		cc*=xx;
    		bb+=cc;
    	}
    }
    cc=dd;
    bb/=cc;
    cout << fixed << setprecision(10) << bb;
    
    
}















int main()
{
	long long int t=1,c=1;
	// scanf("%lld",&t);
	while(t--){
		solve(c);
		c++;
	}
	return 0;
}
/* UJJWAL KESHRI */

Measured memory_bytes: 3820
#include<bits/stdc++.h>
 
#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
 
using namespace std;
 //...
struct Edge { 
  int src,dst,w; 
  bool operator < ( const Edge& e ) const {
    if( w != e.w ) return w < e.w;
    if( src != e.src ) return src < e.src;
    return dst < e.dst;
  }
};
const int MAX_V = 510; //
int V,E; //
vector<Edge> G[MAX_V]; // undirected graph
vector<int> dfs_num,dfs_low,dfs_parent,articulation_vertex;
int dfsNumberCounter, dfsRoot, rootChildren;
int cost[MAX_V][MAX_V];
 
//O(V+E)
int base_weight;
vector<Edge> bridges;
#define UNVISITED -1
void articulationPointAndBridge(int u){
  dfs_low[u] = dfs_num[u] = dfsNumberCounter++;
  rep(j,(int)G[u].size()){
    Edge &v = G[u][j];
    if( dfs_num[v.dst] == UNVISITED ) {
      dfs_parent[v.dst] = u;
      if( u == dfsRoot ) rootChildren++;
 
      articulationPointAndBridge(v.dst);
 
      if( dfs_low[v.dst] >= dfs_num[u] ) articulation_vertex[u] = true;
      if( dfs_low[v.dst] >  dfs_num[u] ) {
        if( base_weight == cost[u][v.dst] ) {
          bridges.push_back((Edge){u,v.dst,base_weight});
        }
        //printf("Edge (%d,%d) is a bridge\n",u,v.dst);
      }
      dfs_low[u] = min(dfs_low[u],dfs_low[v.dst]);
    } else if( v.dst != dfs_parent[u] ) {
      dfs_low[u] = min(dfs_low[u],dfs_num[v.dst]);
    }
  }
}
 
void calculateArticulationPointAndBridge(){
  dfsNumberCounter = 0;
  dfs_num.assign(V,UNVISITED);
  dfs_low.assign(V,0);
  dfs_parent.assign(V,0);
  articulation_vertex.assign(V,0);
   
  rep(i,V) {
    if( dfs_num[i] == UNVISITED ) {
      dfsRoot = i, rootChildren = 0;
      articulationPointAndBridge(i);
      articulation_vertex[dfsRoot] = ( rootChildren > 1 );
    }
  }
}
 
int par[MAX_V];
 
int find(int x){
  if( x == par[x] ) return x;
  return par[x] = find(par[x]);
}
 
void unit(int x,int y){
  x = find(x), y = find(y);
  if( x != y ) par[x] = y;
}
 
 
void compute(vector<Edge> edges){
  set<int> weights;
  rep(i,V) par[i] = i;
  sort(edges.begin(),edges.end());
  rep(i,E){
    Edge &e = edges[i];
    if( find(e.src) != find(e.dst) ) {
      unit(e.src,e.dst);
      weights.insert(e.w);
    }
  }
  int cnt=0,sum=0;
  int cur = 0;
  for(set<int>::iterator it=weights.begin();it!=weights.end();it++){
    int w = *it;
    while( cur < E && edges[cur].w < w ) ++cur;
    if( cur >= E ) break;
    if( edges[cur].w > w ) continue;
    base_weight = w;
    while( cur < E && edges[cur].w == w ) {
      Edge &e = edges[cur++];
      G[e.src].push_back((Edge){e.src,e.dst,e.w});
      G[e.dst].push_back((Edge){e.dst,e.src,e.w});
    }
    bridges.clear();
    calculateArticulationPointAndBridge();
    cnt += (int)bridges.size();
    sum += (int)bridges.size() * w;
  }
  printf("%d %d\n",cnt,sum);
}
 
int main(){
  memset(cost,-1,sizeof(cost));
  vector<Edge> edges;
  scanf("%d %d",&V,&E);
  {
    int s,t,w;
    rep(i,E){
      scanf(" %d %d %d",&s,&t,&w);
      --s, --t;
      edges.push_back((Edge){s,t,w});
      cost[s][t] = cost[t][s] = w;
    }
  }
  compute(edges);
  return 0;
}

Measured memory_bytes: 5076
#include<bits/stdc++.h> 
using namespace std; 
#define ll long long
#define pii pair<int,int>
#define ff first
#define ss second
#define vi vector<int>
#define fo(n) for(int i = 0;i < int(n);i++)
#define foo(a,b) for(int i = int(a);i <= int(b);i++)
#define mk make_pair
#define pb push_back
#define MAXN 2000
#define mod 1000000007
#define all(x) x.begin(),x.end()
#define fastio ios_base:: sync_with_stdio(false)
#define inf (int)1e9

vi col[MAXN];
vi row[MAXN];
vector<string> arr(MAXN);


int main(){

	
	fastio;
	
	int s,w;
	cin >> s >> w;

	fo(s) cin >> arr[i];

	for(int i = 0;i < s;i++){
		for(int j = 0;j < w;j++){
			if(arr[i][j] == '#'){
				row[i].pb(j);
			}
		}
	}

	for(int j = 0;j < w;j++){
		for(int i = 0;i < s;i++){
			if(arr[i][j] == '#'){
				col[j].pb(i);
			}
		}
	}

	int ans = 0;

	for(int i = 0;i < s;i++){
		for(int j = 0;j < w;j++){
			//cout << arr[0][0] << endl;
			if(arr[i][j] == '#') continue;

			int cells = 0;
			auto l_r = lower_bound(all(row[i]),j);

			 if(l_r != row[i].begin()){
			 	l_r--;
			 	cells += j-*l_r-1;
			 }
			 else{
			 	cells += j;
			 }

			 auto h_r = lower_bound(all(row[i]),j);

			 if(h_r != row[i].end()){
			 	cells += *h_r-j;
			 }
			 else{
			 	cells += (w-j);
			 }


			 auto l_c = lower_bound(all(col[j]),i);

			 if(l_c != col[j].begin()){
			 	l_c--;
			 	cells += i-*l_c-1;
			 }
			 else{
			 	cells += i;
			 }

			 auto h_c = lower_bound(all(col[j]),i);

			 if(h_c != col[j].end()){
			 	cells += *h_c-i;
			 }
			 else{
			 	cells += (s-i);
			 }

			 cells -= 1;
			 //cout << i << " " << j << " " << cells << endl;
			 ans = max(ans,cells);
		}
	}

	cout << ans << endl;

	return 0;
 }	

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

const int N = 55;

int n;
int A[N+5],B[N+5],C[N+5];

int main(){
  scanf("%d",&n);
  for(int i=1;i<=n;i++) scanf("%d",&A[i]);
  for(int i=1;i<=n;i++) scanf("%d",&B[i]);
  for(int i=2;i<=n;i++) scanf("%d",&C[i]);
  int ans = 0;
  for(int i=1;i<=n;i++){
    ans+=B[i];
    if(i>1 && A[i] == A[i-1]+1) ans+=C[A[i]];
//    cout << ans << endl;
  }
  cout << ans << endl;
  return 0;
}


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

int main(){
  string S;
  cin >> S;
  for(int i=0;i<S.size();i++){
    if(S.at(i)=='7'){
      cout << "Yes" << endl;
      return 0;
    }
  }
  cout << "No" << endl;
  return 0;
}


Measured memory_bytes: 3592
#include <bits/stdc++.h>
#define LL long long
using namespace std;
 
const int maxn = 20;
int n, m;
bool swaped[maxn], used[maxn], ans;
string s[20];
 
bool check()
{
    memset(used, false, sizeof(used));
    for(int i = 0; i < m; i ++) {
        if(used[i])
            continue;
        for(int j = 0; j < m; j ++) {
            bool cur = true;
            if(i == j || used[j])
                continue;
            for(int k = 0; k < n; k ++) {
                if(s[k][i] != s[n - 1 - k][j]) {
                    cur = false;
                    break;
                }
            }
            if(cur) {
                used[i] = used[j] = true;
                break;
            }
        }
    }
 
    int cnt = 0, noused = -1;
    for(int i = 0; i < m; i ++)
        if(!used[i])
            cnt ++, noused = i;
    if((cnt >= 2 ) || (cnt && (m % 2 == 0)))
        return false;
    for(int i = 0; i < n; i ++)
        if(s[i][noused] != s[n - 1 - i][noused])
            return false;
    return true;
}
 
void dfs(int u, int flag)
{
    if(u == (n + 1)/ 2) {
        if(check()){
            printf("YES");
            exit(0);
        }
        return;
    }
 
    for(int i = u; i < n; i ++) {
        if(!swaped[i]) {
            swaped[i] = true;
            for(int j = i + 1; j < n; j ++) {
                if(swaped[j])
                    continue;
                swaped[j] = true;
 
                dfs(u + 1, flag);
                swap(s[i], s[j]);
                dfs(u + 1, flag);
                swap(s[i], s[j]);
 
                swaped[j] = false;
            }
            if(flag) {
                dfs(u + 1, false);
            }
            swaped[i] = false;
            break;
        }
    }
}
 
int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i ++)
        cin >> s[i];
 
    if(n & 1)
        dfs(0, true);
    else
        dfs(0, false);
    printf("NO");
    return 0;
}

Measured memory_bytes: 256
<?php
    fscanf(STDIN, "%d", $N);
    $a = explode(" ", trim(fgets(STDIN)));
    $b = $a;

    $partA = array_splice($a, 0, $N * 2);
    $originalA = $partA;
    arsort($partA);
    $rawA = $partA;
    rsort($rawA);
    $backupA = $rawA;
    $sumA = array_sum(array_splice($rawA, 0, $N));
    //echo $sumA . PHP_EOL;
    $sortA = array_flip(array_keys($partA));
    //var_dump($partA);
    //exit;
    /*
    echo "sort: ";
    foreach ($sortA as $k => $v) {
        echo "{$k}->{$v} ";
    }
    echo PHP_EOL;
    */

    $line = $N - 1;
    $popA = 0;
    
    $arrA = [$sumA];
    for ($i = $N * 2 - 1; $i >= $N; $i--) {
        //printf("%d %d \n", $sortA[$i], $line);
        if ($sortA[$i] <= $line) {
            $sumA -= $originalA[$i];
            $popA++;

            $line++;
            while (is_null($backupA[$line])) {
                $line++;
            }
            $sumA += $backupA[$line];
            //printf("+ %d - %d # %d\n", $backupA[$line], $backupA[$popA]);
        }
        $backupA[$sortA[$i]] = null;
        $arrA[] = $sumA;
    }
    
    //var_dump($backupA);
    //var_dump($partA);
    //var_dump($arrA);


    $partB = array_splice($b, $N, $N * 2);
    $originalB = $partB;
    asort($partB);
    $rawB = $partB;
    sort($rawB);
    $backupB = $rawB;
    $sumB = array_sum(array_splice($rawB, 0, $N));
    //echo $sumB . PHP_EOL;
    $sortB = array_flip(array_keys($partB));
    //var_dump($partB);
    //exit;
    /*
    echo "sort: ";
    foreach ($sortB as $k => $v) {
        echo "{$k}->{$v} ";
    }
    echo PHP_EOL;
    */

    $line = $N - 1;
    $popB = 0;
    
    $arrB = [$sumB];
    for ($i = 0; $i < $N; $i++) {
        //printf("%d %d \n", $sortB[$i], $line);
        if ($sortB[$i] <= $line) {
            $sumB -= $originalB[$i];
            //var_dump($backupB);
            $popB++;

            $line++;
            while (is_null($backupB[$line])) {
                $line++;
            }
            $sumB += $backupB[$line];
            //printf("+ %d - %d\n", $backupB[$line], $originalB[$i]);
        } else {
            //echo "SKIP \n";
        }
        $backupB[$sortB[$i]] = null;
        $arrB[] = $sumB;
    }
    
    //var_dump($backupA);
    //var_dump($partB);
    //var_dump($arrA);
    //var_dump($arrB);

    $ans = -PHP_INT_MAX;
    foreach ($arrA as $key => $val) {
        $ans = max($ans, $arrA[$key] - $arrB[$N - $key]);
    }
    echo $ans;


Measured memory_bytes: 115232
import java.util.*;
public class Main{
 
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
    int b=sc.nextInt();
    int c=sc.nextInt();
    if(a%2 != 0 || c%2 != 0 || b%2 != 0){
      System.out.println(0);
      System.exit(0);
    }
	int steps = 1;
    int d = a, e = b, f = c;
    int newA = (b/2)+(c/2);
    int newC = (b/2)+(a/2);
    int newB = (a/2)+(c/2);
    a=newA;
    b=newB;
    c=newC;
    while(a%2 ==0 && c%2 ==0&& b%2 ==0){
      newA = (b/2)+(c/2);
      newC = (b/2)+(a/2);
      newB = (a/2)+(c/2);
      a=newA;
      b=newB;
      c=newC;
      if(a == d && b == e && c == f){
        steps = -1;
        break;
      }
      steps++;
    }
    System.out.println(steps);
  }
}

Measured memory_bytes: 21844
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
typedef long long int ll;
ll mod=1000000007;
int gcd(ll a,ll b){ return (b%a==0)?a:gcd(b-a*(b/a),a);}
int main()
{
   ll i,j,k=0,n,t,x;
    string s;cin>>s;
    n=s.length();
    for(i=0;i<n;i++){k+=int(s[i]-'0');}
    if(k%9==0){cout<<"Yes";}
    else{cout<<"No";}
   return 0;
}

Measured memory_bytes: 3748
#!/usr/bin/env python3
n, a = map(int, input().split())
x = list(map(int, input().split()))
s = sum(x)
dp = [[[0] * (s+1) for _ in range(n+1)] for _ in range(n+1)]
dp[0][0][0] = 1
for i in range(1, n+1):
    xi = x[i-1]
    for j in range(s+1):
        for k in range(i):
            dp[i][k][j] = dp[i-1][k][j]
    for j in range(xi, s+1):
        for k in range(1, i+1):
            dp[i][k][j] += dp[i-1][k-1][j-xi]

ans = 0
for i in range(1, n+1):
    if i*a > s:
        break
    ans += dp[n][i][i*a]
print(ans)

Measured memory_bytes: 119388
<?php
fscanf(STDIN, '%d', $cnt);
$people = array_map('intval', explode(' ', trim(fgets(STDIN))));
$limit = max($people);
$ans = 1000000;
for ($i=1; $i <= $limit; $i++) { 
    $tmp = 0;
    foreach ($people as $key => $person) {
        $tmp += (($person - $i)**2);
    }
    $ans = min($ans, $tmp);
}
echo $ans;

Measured memory_bytes: 4728