akhauriyash/Code-Regression huggingface dataset:
# 2K * 2Kの正方形で一周するので、
# (X,Y) -> (X % 2K, Y % 2K)に言い換えることが出来る
# Wの表とBの表を別々で持つ
# それぞれの表で二次元累積和を持ち、範囲に対する得点を求められるようにする
# 黒いK * Kの正方形の左下隅を1000 * 1000通り全探索して最大値を求める

import sys
readline = sys.stdin.readline

N,K = map(int,readline().split())
white = [[0] * (2 * K + 1) for i in range(2 * K + 1)]
black = [[0] * (2 * K + 1) for i in range(2 * K + 1)]
# 黒を数えるときは、同時に白を数えて、白全体の数から引く
white_all = 0
black_all = 0
for i in range(N):
  x,y,c = readline().split()
  x,y = int(x) % (2 * K),int(y) % (2 * K)
  if c == "W":
    white[x + 1][y + 1] += 1
    white_all += 1
  else:
    black[x + 1][y + 1] += 1
    black_all += 1
  
for i in range(1, len(white)):
  for j in range(1, len(white[i])):
    white[i][j] += white[i][j - 1]
    
for j in range(1, len(white)):
  for i in range(1, len(white[j])):
    white[i][j] += white[i - 1][j]

for i in range(1, len(black)):
  for j in range(1, len(black[i])):
    black[i][j] += black[i][j - 1]
    
for j in range(1, len(black)):
  for i in range(1, len(black[j])):
    black[i][j] += black[i - 1][j]


# cases = ((0,0),(K,K),(-K,-K),(K,-K),(-K,K),(-K * 2,-K * 2),(K * 2,K * 2),(-K * 2,0),(K * 2,0),(0,K * 2),(0,-K * 2))
cases = ((0,0),(K,K),(-K,-K),(K,-K),(-K,K))
ans = 0
#test = {}

#for i in range(1, 2 * K + 1):
#  for j in range(1, 2 * K + 1):
#    test[(i,j)] = False
  
for i in range(1, K + 1):
  for j in range(1, K + 1):
#    check = False
#    if i == 2 and j == 3:
#      check = True
    # 基本となる黒の正方形の左下隅・右上は以下の通り
    # (i,j),(i + K - 1, j + K - 1)
    # これに対して、
    # i,jともに +Kしたもの
    # i,jともに -Kしたもの
    # iは+K,jは-Kしたもの
    # iは-K,jは+Kしたもの
    # が考えられる範囲となる
    # なお、最小値は1,1、最大値は2 * K,2 * Kとなる
    black_cnt = 0
    white_cnt = 0
    for c in cases:
      x1 = i + c[0]
      y1 = j + c[1]
      x2 = x1 + K - 1
      y2 = y1 + K - 1
#      if check:
#        print("before",x1,y1,x2,y2)
        
#      if x2 <= 0 or y2 <= 0:
#        continue
#      if x2 >= 2 * K + 1 or y2 >= 2 * K + 1:
#        continue
      x1 = max(1, x1)
      y1 = max(1, y1)
      x2 = min(2 * K, x2)
      y2 = min(2 * K, y2)
#      if check:
#        print("after",x1,y1,x2,y2)
      if x1 > x2 or y1 > y2:
        continue
        
      # その領域の黒と白の数を数える
      black_cnt += black[x2][y2] - black[x2][y1 - 1] - black[x1 - 1][y2] + black[x1 - 1][y1 - 1]
      white_cnt += white[x2][y2] - white[x2][y1 - 1] - white[x1 - 1][y2] + white[x1 - 1][y1 - 1]
      
#      test[(x1,y1)] = True
      
    point = max(black_cnt + (white_all - white_cnt),white_cnt + (black_all - black_cnt))
    if ans < point:
      ans = point
    
#for key,value in test.items():
#  if not value:
#    print(key)

print(ans)

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

using namespace std;

int main() {
  long N;
  cin >> N;
  
  string S;
  cin >> S;
  
  long res = 0;
  char pre = 'X';
  for (const char& c : S) {
    if (c != pre) {
      ++res;
      pre = c;
    }
  }
  cout << res << endl;
  
  return 0;
}


Measured memory_bytes: 512
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> P;
const ll mod = 1e9+7;
const ll INF = 2e9;
const double PI = 3.1415926535;

char x[200001];
int main(void){
    scanf("%s", &x);
    int s = 0, ans = 0, j = 0;
    while(x[j] != '\0'){
        if(x[j] == 'S')s++;
        if(x[j] == 'T')if(s > 0){s--; ans += 2;}
        j++;
    }
    cout << j - ans << endl;
	return 0;
}

Measured memory_bytes: 384
// abc121_b
#include <bits/stdc++.h>
#ifdef LOCAL
#include "../cxx-prettyprint/prettyprint.hpp"
#endif
using namespace std;

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

#define REP(i, n) for (int (i) = 0 ; (i) < (int)(n) ; ++(i))
#define REPN(i, m, n) for (int (i) = m ; (i) < (int)(n) ; ++(i))
#define REP_REV(i, n) for (int (i) = (int)(n) - 1 ; (i) >= 0 ; --(i))
#define REPN_REV(i, m, n) for (int (i) = (int)(n) - 1 ; (i) >= m ; --(i))
#define ALL(x) x.begin(), x.end()

#define INF ((1 << 29)-1)
#define MOD (1000000007)

#define print2D(h, w, arr) REP(i, h) { REP(j, w) cout << arr[i][j] << " "; cout << endl; }
#define print_line(vec, n) {for(int i=0;i<(n-1);i++) cout << (vec)[i] << " "; cout << (vec)[(n)-1] << endl;}
template<class T> void print(const T& x){cout << x << endl;}
template<class T, class... A> void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); }
struct PreMain {PreMain(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(20);}} premain;

int main() {
#ifdef LOCAL
    ifstream in("../arg.txt"); cin.rdbuf(in.rdbuf());
#endif

    int N, M, C;
    cin >> N >> M >> C;

    vector<int> B(M);
    REP(i, M) cin >> B[i];

    int ans = 0;
    REP(i, N){
        vector<int> A(M);
        REP(j, M) cin >> A[j];

        int tmp = C;
        REP(j, M) tmp += A[j] * B[j];

        if (tmp > 0){
            ans++;
        }

    }

    print(ans);

    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#include <queue>
#include <stack>
#include <cstdlib>
#include <map>
#include <iomanip>
#include <set>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define int long long
#define pie 3.141592653589793238462643383279
#define mod 1000000007
#define INF 1145141919364364
#define all(vec) vec.begin(),vec.end()
#define ggr getchar(); getchar();return 0;
#define ll long long
#define P pair<int,int>
#define S second
#define F first
int gcd(int x, int y) {
	if (y == 0)return x;
	return gcd(y, x%y);
}
int lcm(int x, int y) {
	return x / gcd(x, y)*y;
}
bool prime(int x) {
	for (int i = 2; i <= sqrt(x); i++) {
		if (x%i == 0)return false;
	}
	return true;
}

int kai(int x) {
	if (x == 1)return 1;
	return kai(x - 1)*x;
}

int mod_pow(int x, int y, int moder) {
	int res = 1;
	while (y > 0) {
		if (y & 1)res = res * x%moder;
		x = x * x%moder;
		y >>= 1;
	}
	return res;
}

int n, a[364364];
priority_queue<int> que2;
priority_queue <int, vector<int>, greater<int>> que;
int ta;
vector<int> cnt, cnt2;


signed main() {
	cin >> n;
	rep(i, 3 * n)cin >> a[i];
	rep(i, n) {
		que.push(a[i]);
		ta += a[i];
	}
	cnt.push_back(ta);
	for (int i = n; i < 2 * n; i++) {
		if (que.top() < a[i]) {
			ta += a[i] - que.top();
			que.pop();
			que.push(a[i]);
		}
		cnt.push_back(ta);
	}
	ta = 0;
	for (int i = 3 * n - 1; i >= 2 * n; i--) {
		que2.push(a[i]);
		ta += a[i];
	}
	cnt2.push_back(ta);
	for (int i = 2 * n - 1; i >= n; i--) {
		if (que2.top() > a[i]) {
			ta -= que2.top() - a[i];
			que2.pop();
			que2.push(a[i]);
		}
		cnt2.push_back(ta);
	}
	int ans = -INF;
	rep(i, cnt.size()) {
		ans = max(ans, cnt[i] - cnt2[cnt.size() - 1 - i]);
	}
	cout << ans << endl;
}

Measured memory_bytes: 6516
import numpy as np
 
n = int(input())
a = list(map(int, input().split()))
a.sort()
dp = [0 for _ in range(a[-1] + 1)]

for x in a:
    for j in range(x, a[-1] + 1, x):
        dp[j] += 1
ans = 0
for x in set(a):
    #print(x)
    if dp[x] == 1:
        ans += 1
print(ans)

Measured memory_bytes: 59408
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <fstream>
#include <cassert>
#include <cstring>
#include <unordered_set>
#include <unordered_map>
#include <numeric>
#include <ctime>
#include <bitset>
#include <complex>

using namespace std;

signed main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int a, b;
	cin >> a >> b;
	if (a < 10 && b < 10) cout << a * b << endl;
	else cout << -1 << endl;
}


Measured memory_bytes: 256
use std::io::{stdin, Read, StdinLock};
use std::str::FromStr;

#[allow(dead_code)]
struct Scanner<'a> {
    cin: StdinLock<'a>,
}
#[allow(dead_code)]
impl<'a> Scanner<'a> {
    fn new(cin: StdinLock<'a>) -> Scanner<'a> {
        Scanner { cin: cin }
    }

    fn read<T: FromStr>(&mut self) -> Option<T> {
        let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect::<String>();
        token.parse::<T>().ok()
    }

    fn input<T: FromStr>(&mut self) -> T {
        self.read().unwrap()
    }

    fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> {
        (0..len).map(|_| self.input()).collect()
    }

    fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> {
        (0..row).map(|_| self.vec(col)).collect()
    }
}

fn main() {
    let cin = stdin();
    let cin = cin.lock();
    let mut sc = Scanner::new(cin);

    let n: usize = sc.input();
    let a: usize = sc.input();
    let b: usize = sc.input();
    let c: usize = sc.input();
    let ss: Vec<String> = sc.vec(n);

    let mut ans = vec![];
    dfs(0, a as i64, b as i64, c as i64, &ss, &mut ans);

    if ans.len() == 0 {
        println!("{}", "No");
    } else {
        println!("{}", "Yes");
        ans.reverse();
        for ch in ans {
            println!("{}", ch);
        }
    }
}


fn dfs(cur: i64, a: i64, b: i64, c: i64, ss: &Vec<String>, mut ans: &mut Vec<char>) -> bool {
    let n = ss.len();
    if cur == n as i64 {
        return true;
    }

    match &*ss[cur as usize] {
        "AB" => {
            if a == 0 && b == 0 {
                false
            } else if 0 < a && dfs(cur + 1, a - 1, b + 1, c, &ss, &mut ans) {
                ans.push('B');
                true
            } else if 0 < b && dfs(cur + 1, a + 1, b - 1, c, &ss, &mut ans) {
                ans.push('A');
                true
            } else {
                false
            }
        },
        "AC" => {
            if a == 0 && c == 0 {
                false
            } else if 0 < a && dfs(cur + 1, a - 1, b, c + 1, &ss, &mut ans) {
                ans.push('C');
                true
            } else if 0 < c && dfs(cur + 1, a + 1, b, c - 1, &ss, &mut ans) {
                ans.push('A');
                true
            } else {
                false
            }
        },
        "BC" => {
            if b == 0 && c == 0 {
                false
            } else if 0 < b && dfs(cur + 1, a, b - 1, c + 1, &ss, &mut ans) {
                ans.push('C');
                true
            } else if 0 < c && dfs(cur + 1, a, b + 1, c - 1, &ss, &mut ans) {
                ans.push('B');
                true
            } else {
                false
            }
        }
        _ => unreachable!()
    }
}


Measured memory_bytes: 14208
#include <climits>
#include <cmath>
#include <algorithm>
#include <array>
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int main(int, char**)
{
	int N;
	cin >> N;
	vector<vector<int>> A(N, vector<int>(N - 1));
	for (int i = 0; i < N; ++i)
	{
		for (int j = 0; j < N - 1; ++j)
		{
			int a;
			cin >> a;
			A[i][j] = a - 1;
		}
	}
	vector<int> n(N, 0);
	long day = 0;
	long match = 0;
	const long longest = N * (N - 1) / 2;
	while (match < longest)
	{
		vector<bool> done(N, false);
		bool found = false;
		for (int i = 0; i < N; ++i)
		{
			if (n[i] == N - 1)	continue;
			const int target = A[i][n[i]];
			if (done[i] || done[target])	continue;
			if (i == A[target][n[target]])
			{
				++match;
				found = true;
				done[i] = true;
				done[target] = true;
				++n[i];
				++n[target];
			}
		}
		if (!found)	break;
		++day;
	}
	if (match == longest)
	{
		cout << day << endl;
	}
	else
	{
		cout << -1 << endl;
	}
	return 0;
}


Measured memory_bytes: 6272
#include<bits/stdc++.h>
using namespace std;
int main(){
  int a,b;
  double m;
  while(cin>>a>>b,a!=0&&b!=0){
    m=1e5;
    for(int i=0;i<=a/2;i++){
      int j=a-i;
     m=min(m,abs(sqrt(i*i+j*j)-b));
  }
  printf("%.10f\n",m);
  }
  return 0;
}

Measured memory_bytes: 1196
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
#include <tuple>
#include <algorithm>
#include <queue>
#define rep(i,n) for (int i=0; i<n; ++i)
using namespace std;

struct camel {
    int k=0,h=0;
};
using camelgroup = vector<camel>;

void extract(priority_queue<int>& pool, camelgroup& t, int k) {
    while (t.size()) {
        if (t.back().k >= k) {
            pool.push(t.back().h);
            t.pop_back();
            continue;
        }
        break;
    }
}

int main() {
    int t;
    cin >> t;
    rep(i,t) {
        camelgroup red, blue;
        long long ans = 0;
        int n;
        cin >> n;
        rep(j,n) {
            int k,l,r;
            cin >> k >> l >> r;
            int m = min(l, r);
            ans += m;
            if (l > r)
                red.push_back({k,l-m});
            else
                blue.push_back({n-k,r-m});
        }

        auto lessk = [](camel& c1, camel& c2){ return c1.k < c2.k; };
        sort(red.begin(), red.end(), lessk);
        sort(blue.begin(), blue.end(), lessk);

        auto dis = [&](camelgroup& g){
            priority_queue<int> pool;
            for (int k=g.size(); k > 0; --k) {
                extract(pool, g, k);
                if (pool.size()) {
                    ans += pool.top();
                    pool.pop();
                }
            }
        };
        dis(red);
        dis(blue);

        cout << ans << endl;
    }
}


Measured memory_bytes: 5716
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define sz(x) ((int)(x).size())
typedef vector<int> vi;
typedef long long ll;
typedef pair<int,int> pii;
typedef double db;
const ll mod=1000000007;
ll powmod(ll a,ll b) {ll res=1;a%=mod;assert(b>=0);for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	double a,b;
	cin>>a>>b;
	if(a>=13){
		cout<<b;
		return 0;
	}
	if(a>=6){
		cout<<b/2;
		return 0;
	}
	else{
		cout<<0;
		return 0;
	}
	
}

Measured memory_bytes: 3772
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <utility>
#include <functional>
#include <iomanip>
#include <typeinfo>
#include <iterator>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <tuple>
#include <map>
#include <set>
using namespace std;

typedef long long       ll;
typedef vector<int>     vi;
typedef vector<ll>      vll;
typedef vector<double>  vd;
typedef vector<bool>    vb;
typedef vector<string>  vs;
typedef vector<char>    vc;
typedef pair<int, int>  pii;
typedef pair<ll, ll>    pll;
typedef vector<pii>     vpii;
typedef vector<pll>     vpll;

// マクロ
#define repr(itr, bgn, end) for (ll itr = (ll)bgn; itr < (ll)end; itr++)
#define rep(itr, end) repr(itr, 0, end)
#define reprrev(itr, bgn, end) for (ll itr = (ll)end - 1; itr >= (ll)bgn; i--)
#define reprev(itr, end) reprrev(i, 0, end)
#define all(container) container.begin(), container.end()
#define yn(cond) cond ? (cout << "Yes" << endl) : (cout << "No" << endl)
#define YN(cond) cond ? (cout << "YES" << endl) : (cout << "NO" << endl)

// 定数
#define LLONG_MAX 9223372036854775807i64
constexpr double PI = 3.14159265358979323846;
constexpr ll INF = 1 << 15;
constexpr ll MOD = (ll)1e9 + 7;
constexpr double EPS = 1e-7;

// よく使うもの
constexpr int dy[4] = { 0, 1, 0, -1 };
constexpr int dx[4] = { 1, 0, -1, 0 };
struct edge { ll to; ll cost; };


// vector入力
template<typename T>
istream& operator >> (istream& is, vector<T>& vec) {
    for (T& x : vec) is >> x;
    return is;
}

// vector出力
template<typename T>
ostream& operator << (ostream& os, vector<T>& vec) {
    for (T& x : vec) os << x << endl;
    return os;
}

// ***<ここから>****************************************************************

int main(void) {

    int N;

    cin >> N;
    if (N % 2 == 0) cout << N << endl;
    else cout << N * 2 << endl;

 
    return 0;
}

Measured memory_bytes: 256
#include "bits/stdc++.h"
#include <set>
using namespace std;
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define RFOR(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep1(i, n) for (int i = 1; i < (n); i++)
#define rrep(i, n) for (int i = (n)-1; i >= 0; i--)
#define all(i) (i).begin(), (i).end()
#define rall(i) (i).begin(), (i).end(), greater<int>()
#define int long long
#define elif else if
#define eb emplace_back
#define pb push_back
#define mp make_pair
#define fst first
#define sec second
#define mod 1000000007
#define INF 10e10
template <typename T>

void print(T x)
{
	std::cout << x << " ";
}
template <typename T>

void println(T x)
{
	std::cout << x << "\n";
}

int dp[100001];

signed main(void) {
	int N,W;
	cin >> N>>W;
	vector<int>w(N),v(N);
	rep(i, N) {
		cin >> w[i]>>v[i];
		dp[i] = 0;
	}
	rep(i, N) {
		rrep(j, W + 1) {
			if (j >= w[i]) {
				dp[j] = max(dp[j], dp[j - w[i]] + v[i]);
			}
		}
	}
	print(dp[W]);
}

Measured memory_bytes: 1024
#include <iostream>

int main() {
    long long n, ret = 0, tmp;
    std::cin >> n;
    for (long long i = 0; i < n; i++) {
        std::cin >> tmp;
        while ((tmp & 1) == 0) {
            tmp >>= 1;
            ret++;
        }
    }

    std::cout << ret << std::endl;
}

Measured memory_bytes: 764
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;
int a[1024];
int main()
{
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	sort(a,a+n);
	cout<<a[n-1]-a[0]<<endl;
	return 0;
}

Measured memory_bytes: 256
#!/usr/bin/env python3
import sys

YES = "Yes"  # type: str
NO = "No"  # type: str

def solve(S: str):
    length = len(S)
    if length % 2 != 0:
        print(NO)
        return
    
    for i in range(length):
        if i % 2 == 0 and S[i] != "h":
            print(NO)
            return
        elif i % 2 != 0 and S[i] != "i":
            print(NO)
            return

    print(YES)

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    S = next(tokens)  # type: str
    solve(S)

if __name__ == '__main__':
    main()


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

int main() {
  ll N, K; cin >> N >> K;
  ll a[N];
  for (ll i = 0; i < N; i++) {
    cin >> a[i];
  }
  ll x; ll m = 1e5;
  for (ll i = 0; i < N; i++) {
    if (m > a[i]) {x = i+1;}
  }
  ll res = (x-1+K-2)/(K-1);
  ll y = min(N,res*(K-1)+1);
  ll rem = N-y;
  res += (rem+K-2)/(K-1);
  cout << res << endl;
}

Measured memory_bytes: 1024
def main():
    n, m = map(int, input().split())
    h_lst = list(map(int, input().split()))

    ab_dict = dict()  # 展望台i : [展望台iに隣接する展望台の標高]
    for _ in range(m):
        a, b = map(int, input().split())

        if a not in ab_dict:
            ab_dict[a] = [h_lst[b - 1]]
        else:
            ab_dict[a].append(h_lst[b - 1])

        if b not in ab_dict:
            ab_dict[b] = [h_lst[a - 1]]
        else:
            ab_dict[b].append(h_lst[a - 1])

    cnt = 0
    ab_dict_keys = ab_dict.keys()
    for i in range(1, n + 1):
        if i not in ab_dict_keys:
            cnt += 1
            continue
        if h_lst[i - 1] > max(ab_dict[i]):
            cnt += 1

    print(cnt)


if __name__ == "__main__":
    main()


Measured memory_bytes: 97820
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cassert>
#include<cmath>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<queue>
#include<stack>
using namespace std;
#define MOD 1000000007
#define MOD2 998244353
#define INF ((1<<30)-1)
#define LINF (1LL<<60)
#define EPS (1e-10)
typedef long long Int;
typedef pair<Int, Int> P;

int n, W;
Int dp[110][110000];
Int w[110], v[110];

int main(){
    cin >> n >> W;
    for(int i = 1;i <= n;i++)cin >> w[i] >> v[i];
    for(int j = 1;j < 110000;j++){
        dp[0][j] = LINF;
    }
    for(int i = 1;i <= n;i++){
        for(int j = 0;j < 110000;j++){
            dp[i][j] = dp[i-1][j];
            if(j-v[i] >= 0){
                dp[i][j] = min(dp[i][j], dp[i-1][j-v[i]] + w[i]);
            }
        }
    }
    int ans = 0;
    for(int v = 0;v < 110000;v++){
        if(dp[n][v] <= W){
            ans = max(ans, v);
        }
    }
    cout << ans << endl;
    
    return 0;
}


Measured memory_bytes: 88320
import sys
input = sys.stdin.readline

def main():
    n=int(input())
    x=list(map(int,input().split()))
    mans=100**4
    for i in range(1,101):
        ans=0
        for j in x:
            ans+=(j-i)**2
        mans=min(mans,ans)
    print(mans)

if __name__ == '__main__':
    main()

Measured memory_bytes: 38768
#include<stdio.h>
#include<string.h>
int main(void)
{
    char a[11], b[11], c[11];
    scanf("%s %s %s", a, b, c);

    if(a[strlen(a)-1] == b[0] && b[strlen(b)-1] == c[0]) printf("YES");
    else printf("NO");

    return 0;
}

Measured memory_bytes: 128
def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod


mod = 10**9+7 #出力の制限
N = 10**5
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 )

n, k = map(int, input().split())
a = list(map(int, input().split()))
mod = 10 ** 9 + 7

a.sort()

ans = 0
for i in range(n - k + 1):
    ans += cmb(n - i - 1, k - 1, mod) * (a[n-i-1] - a[i])
    ans %= mod

print(ans)


Measured memory_bytes: 26708
using System;
using System.Linq;
class c
{
    static void Main()
    {
        Console.ReadLine();
        var inp = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
        int ans = inp[0];
        for (int i = 1; i < inp.Count(); i++)
        {
            ans = GCD(ans, inp[i]);
        }
        Console.WriteLine(ans);
    }
    static int GCD(int x, int y)
    {
        if (x > y) return GCD(y, x);
        while (y % x != 0)
        {
            int temp = y % x;
            y = x;
            x = temp;
        }
        return x;
    }
}

Measured memory_bytes: 18528
#!/usr/bin/env python3
# %%
import numpy as np
# %%
stdin = open(0)

# %%
N, K = map(int, stdin.read().split())

# %%
MOD = 10 ** 9 + 7

# %%


def cumprod(A, MOD=MOD):
    L = len(A)
    Lsq = int(L**.5 + 1)
    A = np.resize(A, Lsq**2).reshape(Lsq, Lsq)
    for n in range(1, Lsq):
        A[:, n] *= A[:, n - 1]
        A[:, n] %= MOD
    for n in range(1, Lsq):
        A[n] *= A[n - 1, -1]
        A[n] %= MOD
    return A.ravel()[:L]


def make_fact(U, MOD=MOD):
    x = np.arange(U, dtype=np.int64)
    x[0] = 1
    fact = cumprod(x, MOD)
    x = np.arange(U, 0, -1, dtype=np.int64)
    x[0] = pow(int(fact[-1]), MOD - 2, MOD)
    fact_inv = cumprod(x, MOD)[::-1]
    fact.flags.writeable = False
    fact_inv.flags.writeable = False
    return fact, fact_inv


# %%
fact, fact_inv = make_fact(N + 10)

# %%
if K >= N:
    K = N - 1
x = fact[N] * fact_inv[0:K + 1] % MOD * fact_inv[N - K:N + 1][::-1] % MOD
y = fact[N - 1] * fact_inv[0:K + 1] % MOD * fact_inv[N - K - 1:N][::-1] % MOD
answer = np.sum(x * y % MOD) % MOD

# %%
print(answer)

# %%


Measured memory_bytes: 24972
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        //値を取得
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] B = new int[N-1];
        for (int i = 0; i < (N-1); ++i){
            B[i]= sc.nextInt();
        }
        
        //加算
        int sum = B[0] + B[N-2];
        for (int i = 0; i < (N-2); ++i){
            sum += Math.min(B[i],B[i+1]);
        }
        
        //出力
        System.out.println(sum);
        
    }
}

Measured memory_bytes: 35812
// tsukasa_diary's programing contest code template
#include <bits/stdc++.h>
using namespace std;
// define
#define for_(i,a,b) for(int i=a;i<b;++i)
#define for_rev(i,a,b) for(int i=a;i>=b;--i)
#define allof(a) a.begin(),a.end()
#define minit(a,b) memset(a,b,sizeof(a))
#define size_of(a) (int)a.size()
// typedef
typedef long long lint;
typedef double Double;
typedef pair<int, int> pii;
//
typedef vector< int > Array;
typedef vector< Array > Matrix;
typedef vector< Double > DArray;
typedef vector< DArray > DMatrix;
typedef vector< string > SArray;
typedef vector< pii > PArray;
// popcount
inline int POPCNT(int _x) { return __builtin_popcount(_x); }
inline int POPCNT(lint _x) { return __builtin_popcountll(_x); }
// inf
const int iINF = 1L << 30;
const lint lINF = 1LL << 60;
// eps
Double EPS = 1e-9;
// in range
inline bool in_range(int _v, int _mx, int _mi) { return _mi <= _v && _v < _mx; }
inline bool in_range(Double _v, Double _mi, Double _mx) { return -EPS < _v - _mi && _v - _mx < EPS; }
inline bool in_range(int _x, int _y, int _W, int _H) { return 0 <= _x && _x < _W && 0 <= _y && _y < _H; }
// neighbor clockwise
const int DX[4] = {0,1,0,-1}, DY[4] = {-1,0,1,0};
const int DX_[8] = {0,1,1,1,0,-1,-1,-1}, DY_[8] = {-1,-1,0,1,1,1,0,-1};
// variable update
inline void modAdd(int& _a, int _b, int _m) { _a = (_a + _b) % _m; }
inline void modAdd(lint& _a, lint _b, lint _m) { _a = (_a + _b) % _m; }
inline void minUpdate(int& _a, int _b) { _a = min(_a, _b); }
inline void minUpdate(lint& _a, lint _b) { _a = min(_a, _b); }
inline void maxUpdate(int& _a, int _b) { _a = max(_a, _b); }
inline void maxUpdate(lint& _a, lint _b) { _a = max(_a, _b); }

int n;

void rec(int x, Array& v, int sum) {
	if (sum > n) return;
	
	int len = size_of(v);
	
	if (sum == n) {
		for_(i,0,len) {
			if (i < len - 1) cout << v[i] << " ";
			else cout << v[i] << endl;
		}
	}

	for_rev(i,x,1) {
		if (len > 0 && v[len - 1] < i) continue;
		v.push_back(i);
		rec(max(i, x - i), v, sum + i);
		v.pop_back();
	}
}

void solve() {
	Array v;
	rec(n, v, 0);
}

int main() {
	while (cin >> n, n) {
		solve();
	}
	return 0;
}

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

class Program {
    static void Main(string[] args) {
        int a = Cin.Ni();
        int b = Cin.Ni();
        int c = Cin.Ni();
        for (int i = 1; i < 100000; i++) {
            if ((a * i) % b == c) {
                Console.WriteLine("YES");
                return;
            }
        }
        Console.WriteLine("NO");

    }
}


public class Cin {
    private static string[] s = new string[0];
    private static int i = 0;

    private static char[] cs = new char[] { ' ' };

    public static string Next() {
        if (i < s.Length) return s[i++];
        string st = Console.ReadLine();
        while (st == "") st = Console.ReadLine();
        s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
        i = 0;
        return Next();
    }

    public static int Ni() {
        return int.Parse(Next());
    }

    public static long NextLong() {
        return long.Parse(Next());
    }

    public static double NextDouble() {
        return double.Parse(Next());
    }

}


Measured memory_bytes: 13140
import sys
def input(): return sys.stdin.readline().strip()

def resolve():
    import numpy as np
    n,d=map(int, input().split())
    l=[list(map(int,input().split())) for i in range(n)]
    cnt=0
    for j in range(n-1):
        for k in range(j+1,n):
            a=np.array(l[j])-np.array(l[k])
            if np.linalg.norm(a)%1==0:
                cnt+=1
    print(cnt)
resolve()

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

using namespace std;
typedef long long ll;
#define sint(a) scanf("%d",&a)
#define sint2(a,b) scanf("%d %d",&a,&b)
#define sll(a) scanf("%lld",&a)
#define sll2(a,b) scanf("%lld %lld",&a,&b)
#define mem(a,i) memset(a,i,sizeof(a))

const double pi=acos(-1);
const int mod=1e9+7;
const int maxn=1e4+10;

int main()
{
    int n;
    cin>>n;
    int a,f=0;
    for(int i=0;i<n;i++)
    {
       cin>>a;
       if(a%2==0)
       {
           if(a%3&&a%5)
             f=1;
       }
    }
    if(f)
        cout<<"DENIED";
    else
        cout<<"APPROVED";
    return 0;
}


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

int main() {
  int h,w,k;
  cin>>h>>w>>k;
  string board[h];
  for(int i=0; i<h; i++) cin>>board[i];

  // cout<<"0K"<<endl;

  string copy[h];
  int ans = 0;
  for(int bit=0; bit<(1<<(h+w)); bit++) {
    // cout<<"OK"<<endl;
    for(int i=0; i<h; i++) copy[i]=board[i];
    for(int i=0; i<12; i++) {
      if((bit>>i)&1) {
        if(i<h) {
          for(int j=0; j<w; j++) copy[i][j]='r';
        }
        else {
          for(int j=0; j<h; j++) copy[j][i-h]='r';
        }
      }
    }

    int count = 0;
    for(int i=0; i<h; i++) {
      for(int j=0; j<w; j++) {
        if(copy[i][j]=='#') count++;
      }
    }

    if(count==k) ans++;
  }

  cout<<ans<<endl;

  return 0;
}

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

int min(int a , int b){
    if(a>=b) return b;
    return a ;
}

int main()
{

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

  int ans = 0;
  ans+=b[n-2] ;
  for(int i=n-2;i>0;--i){
      ans+= min(b[i-1],b[i]) ;
  }
      ans+= b[0] ;  
  
  cout << ans << endl;
    return 0;
}



Measured memory_bytes: 256
from operator import itemgetter

N=int(input())
A=[]
B=[]
for i in range(N):
  temp=list(map(int, input().split()))
  A.append(temp)
for i in range(N):
  temp=list(map(int, input().split()))
  B.append(temp)
  

def main():
  A.sort(key=itemgetter(0,1))
  B.sort(key=itemgetter(0,1))
  #print(A)
  #print(B)
  cnt=0
  while B!=[]:
    idx=-1
    y=-1
    for i in range(len(A)):
      if A[i][0]>=B[0][0]:
        break
      if A[i][1]<B[0][1] and y<=A[i][1]:
        idx=i
        y=A[i][1]
    if idx!=-1:
      cnt+=1
      #print(A[idx],B[0])
      del A[idx]
      del B[0]
    else:
      del B[0]
  print(cnt)

main()


Measured memory_bytes: 3188
#include<iostream>
#include<algorithm>

using namespace std;

int main() {
	int L,D;
	cin >> L >> D;
	int ans = 100000;
	for (int Lc = 0; Lc <= L; Lc++) {

		if ((L - Lc)%D==0) {
			ans = min(ans, (int)(L - Lc) / D + Lc);
		}
	}
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 3108
#include <bits/stdc++.h>
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  for(int i=0;i<(n);++i)
#define REPr(i,n) for(int i=(n)-1;i>=0; --i)
#define FORq(i, m, n) for(int i = (m);i <= (n);++i)
#define rFORq(i, m , n) for(int i = (n);i >=(m);--i)
#define SCD(n) scanf("%d",&n)
#define SCD2(m,n) scanf("%d%d",&m,&n)
#define SCD3(m,n,k) scanf("%d%d%d",&m,&n,&k)
#define SCLLD(n) scanf("%lld",&n)
#define SCLLD2(m,n) scanf("%lld%lld",&m,&n)
#define SCLLD3(m,n,k) scanf("%lld%lld%lld",&m,&n,&k)
#define PB push_back
#define MP make_pair
#define ARSCD(A,N) REP(i,N){SCD(A[i]);}
#define ARSCD1(A,N) FORq(i,1,N){SCD(A[i]);}
#define VSCD(v,N) REP(i,N){int x; SCD(x); v.PB(x);}
#define VSCLLD(v,N) REP(i,N){long long x; SCLLD(x); v.PB(x);}
#define PRINTD(n) printf("%d\n",n)
#define PRINTLLD(n) printf("%lld\n",n)
#define DEBUG printf("%s\n","debug")
#define fst first
#define snd second
#define SIN(x,S) (S.count(x) != 0)
using namespace std;
typedef pair<int,int> PII;
typedef vector<int> VI;
typedef vector < VI > VVI;
typedef vector<long long> VL;
typedef long long ll;
typedef long long integer;
////////////////////////////////////////////////////////////////////

vector<pair<ll,ll> > prime_fac(ll n){
	vector<pair<ll,ll> >ret;
	for(ll p = 2; p * p <= n; ++p){
		if (n % p != 0) continue;
		int divc = 0;
		while(n % p == 0){
			++divc;
			n /= p;
		}
		ret.PB(MP(p,divc));
	}
	if (n != 1) ret.PB(MP(n,1));

	return ret;
}

int main(){
    ll N,n;
    SCLLD(N);
    ll fac[102] = {};
    FORq(k,1,N){
        n = k;
        for(ll p = 2; p * p <= n; ++p){
            if (n % p != 0) continue;
            int divc = 0;
            while(n % p == 0){
                ++divc;
                n /= p;
            }

            fac[p] += divc;
        }
        if (n != 1) fac[n] += 1;
    }
    REP(i,N+1){
        //printf("fac[%d] = %d\n",i,fac[i]);
    }

    int o74,o2,o14,o24,o4;
    o74 = o2 = o14 = o24 = o4 = 0;
    FORq(i,1,100){
        int num = fac[i];
        if (num >= 74) o74++;
        if (num >= 24) o24++;
        if (num >= 14) o14++;
        if (num >= 4) o4++;
        if (num >= 2) o2++;
    }
    int ans1,ans2,ans3,ans4;
    ans1 = o74;
    ans2 = max(0,o24 * (o24 - 1) / 2) * 2 + (o24 * (o2-o24));
    ans3 = max(0,o14 * (o14 - 1) / 2) * 2 + (o14 * (o4-o14));
    ans4 = max(0,o4 * (o4-1) * (o4-2) / 6) * 3 + max(0,o4*(o4-1) * (o2-o4) / 2);

    int ans = ans1 + ans2 + ans3 + ans4;
    PRINTD(ans);
}

Measured memory_bytes: 256
def trace( nums ):
	output = []
	for num in nums:
		output.append( str( num ) )
		output.append( " " )
	output.pop( )
	print( "".join( output )  )

n = int( input( ) )
nums = [ int( val ) for val in input( ).split( " " ) ]
trace( nums )

for i in range( 1, len( nums ) ):
	key = nums[i]
	j = i - 1
	while 0 <= j and key < nums[j]:
		nums[ j+1 ] = nums[j]
		j -= 1
	nums[ j+1 ] = key
	trace( nums )

Measured memory_bytes: 6724
#include <bits/stdc++.h>
    constexpr int INF = 2147483647;
    constexpr long long int INF_LL = 9223372036854775807;
    constexpr int MOD = 1000000007;
    using namespace std;
    typedef long long int ll;
    typedef unsigned long long int ull;
     
    bool isOK(ll k, vector<ll>& A, ll M) {
    	ll cnt = 0;
    	for (int i = A.size()-1; i >= 0; i--) {
    		auto itr = lower_bound(A.begin(), A.end(), k - A[i]);
    		cnt += (A.end() - itr);
    	}
    	return cnt >= M;
    }
    //最小の幸福度をもたらす握手のスコア
    ll calcMinScore(vector<ll> A, ll M, ll N) {
    	ll ng = A.back()+A.back()+1; //「index = 0」が条件を満たすこともあるので、初期値は -1
    	ll ok = A[0]+A[0]-1; // 「index = a.size()-1」が条件を満たさないこともあるので、初期値は a.size()
     
    	/* ok と ng のどちらが大きいかわからないことを考慮 */
    	while (abs(ok - ng) > 1) {
    		ll mid = (ok + ng) / 2;
     
    		if (isOK(mid, A, M)) ok = mid;
    		else ng = mid;
    	}
    	return ok;
    }
    int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
    	ll N, M;
    	cin >> N >> M;
    	vector<ll> A(N), S(N+1,0);
    	for (int i = 0; i < N; i++) {
    		cin >> A[i];
    	}
    	sort(A.begin(), A.end());
    	for (int i = 0; i < N; i++) {
    		S[i + 1] = S[i] + A[i];
    	}
     
    	ll ms = calcMinScore(A, M, N);
    	ll ans = 0;
    	ll tmp = 0;
    	for (int i = A.size() - 1; i >= 0; i--) {
    		ll cnt;
    		auto itr = upper_bound(A.begin(), A.end(), ms - A[i]);
    		cnt = (A.end() - itr);
    		tmp += cnt;
    		ans += A[i] * cnt + S[N]-S[N-cnt];
    	}
    	if(tmp<M)ans += (M-tmp)*ms;
    	cout << ans << endl;
    }

Measured memory_bytes: 2560
#include <bits/stdc++.h> 
using namespace std; 
#define ll long long
const int max_n = 1e5;
const ll mod = 998244353;
const ll INF = 1LL<<60;
#define fo(i,n) for( ll int i=0;i<n;++i)
#define fos(j,i,n) for(ll int j=i;j<n;++j)
#define N 100004
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define pb push_back
#define mp make_pair
#define all(v) v.begin(),v.end()
#define abs(x) (x<0?(-x):x)
#define dis(k) cout << k << endl
#define forr(i,n) for( ll int i= n-1;i>=0;--i)
#define dbg(vari) cerr<<#vari<<" = "<<(vari)<<endl;
typedef vector< ll int > vi;
typedef vector< vi > vvi;
typedef pair< ll int,ll int > ii;
bool pali(string s, int st,int e){
	while(st<e){
		if(s[st++]!=s[e--])
			return false;
	}
	return true;
}
int main(){
	fast;
	int t;
	t=1;
	//cin >> t;
	while(t--){
		string s;
		cin >> s;
		int n=s.length();
		if(pali(s,0,(n-1)/2-1) && pali(s,(n+3)/2-1,n-1) && pali(s,0,n-1))
			dis("Yes");
		else
			dis("No");

	}
	return 0;
}


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

int e;

int main() {
  while (1) {
    scanf("%d", &e);
    if (e == 0) return 0;

    int ans = e;
    for (int z=0; z*z*z<=e; z++) {
      int z3 = z*z*z;
      for (int y=0; y*y+z3<=e; y++) {
        int y2 = y*y;
        ans = min(ans, y+z+e-y2-z3);
      }
    }

    printf("%d\n", ans);
  }
}

Measured memory_bytes: 3156
#![allow(unused_imports)]

use std::{cmp, fmt};
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::{self, BufWriter, Read, StdinLock, Write};
use std::ops::{Add, Div, Mul, Sub};
use std::str::{self, FromStr};

fn main() {
    let (n, k): (u64, u64) = {
        let stdin = io::stdin();
        let mut sc = Scanner::new(stdin.lock().bytes());
        (sc.next(), sc.next())
    };
    let r = (k + 1..n + 1)
        .map(|b| {
            if k == 0 {
                n
            } else {
                let n1 = (n / b) * (b - k);
                let n2 = cmp::max(n % b + 1, k) - k;
                n1 + n2
            }
        })
        .sum::<u64>();
    println!("{}", r);
}

struct Scanner<R: Read> {
    buf: Vec<u8>,
    bytes: io::Bytes<R>,
}

#[allow(dead_code)]
impl<R: Read> Scanner<R> {
    fn new(bytes: io::Bytes<R>) -> Self {
        Scanner {
            buf: Vec::with_capacity(1024),
            bytes: bytes,
        }
    }

    fn next<T: FromStr>(&mut self) -> T
    where
        <T as FromStr>::Err: fmt::Debug,
    {
        let buf = &mut self.buf;
        buf.clear();
        self.bytes
            .by_ref()
            .map(Result::unwrap)
            .skip_while(|&c| c == b' ' || c == b'\n')
            .take_while(|&c| !(c == b' ' || c == b'\n'))
            .foreach(|c| buf.push(c));
        str::from_utf8(buf).unwrap().parse().unwrap()
    }

    fn vec<T: FromStr>(&mut self, n: usize) -> Vec<T>
    where
        <T as FromStr>::Err: fmt::Debug,
    {
        (0..n).map(|_| self.next()).collect()
    }

    fn pairs<T1: FromStr, T2: FromStr>(&mut self, n: usize) -> Vec<(T1, T2)>
    where
        <T1 as FromStr>::Err: fmt::Debug,
        <T2 as FromStr>::Err: fmt::Debug,
    {
        (0..n).map(|_| (self.next(), self.next())).collect()
    }

    fn trios<T1: FromStr, T2: FromStr, T3: FromStr>(&mut self, n: usize) -> Vec<(T1, T2, T3)>
    where
        <T1 as FromStr>::Err: fmt::Debug,
        <T2 as FromStr>::Err: fmt::Debug,
        <T3 as FromStr>::Err: fmt::Debug,
    {
        (0..n)
            .map(|_| (self.next(), self.next(), self.next()))
            .collect()
    }

    fn mat<T: FromStr>(&mut self, m: usize, n: usize) -> Vec<Vec<T>>
    where
        <T as FromStr>::Err: fmt::Debug,
    {
        (0..m).map(|_| self.vec(n)).collect()
    }

    fn strings_as_mat<T, F: FnMut(u8) -> T>(&mut self, h: usize, mut f: F) -> Vec<Vec<T>> {
        (0..h)
            .map(|_| {
                self.bytes
                    .by_ref()
                    .map(Result::unwrap)
                    .skip_while(|&c| c == b' ' || c == b'\n')
                    .take_while(|&c| !(c == b' ' || c == b'\n'))
                    .map(&mut f)
                    .collect()
            })
            .collect()
    }
}

trait Foreach {
    type Item;
    fn foreach<F: FnMut(Self::Item)>(self, f: F);
}

impl<T, I: Iterator<Item = T>> Foreach for I {
    type Item = T;

    fn foreach<F: FnMut(T)>(self, mut f: F) {
        self.fold((), move |(), x| f(x));
    }
}


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

int main() {
  int n,m;cin>>n>>m;
  vector<int> wa(n),ac(n);
  int cnt1=0,cnt2=0;
  rep(i,m){
    int p;string s;cin>>p>>s;
    p--;
    if(s=="WA")wa[p]++;
    else{
      if(ac[p]==0){
        ac[p]++;
        cnt2+=wa[p];
        cnt1++;
      }
    }
  }
  cout<<cnt1<<" "<<cnt2<<" "<<endl;
}

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

#define eb emplace_back
#define pb push_back
#define ll long long
#define ld long double
#define mp make_pair
#define ull unsigned long long
#define all(s) s.begin(), s.end()
#define sz(a) (int)a.size()

const int INF = (int)1e9 + 7;
const int N = (int)7070 + 7;
const int MAXN = (int)5e5 + 228;

using namespace std;

int n, k, a[MAXN];

list<pair<int, int> > mn, mx;
void add_mn(int x) {
  int cnt = 1;
  while (!mn.empty() && mn.back().first >= x) {
    cnt += mn.back().second;
    mn.pop_back();
  }
  mn.push_back({x, cnt});
}

void del_mn() {
  mn.front().second--;
  if (!mn.front().second) mn.pop_front();
}

void del_mx() {
  mx.front().second--;
  if (!mx.front().second) mx.pop_front();
}
void add_mx(int x) {
  int cnt = 1;
  while (!mx.empty() && mx.back().first <= x) {
    cnt += mx.back().second;
    mx.pop_back();
  }
  mx.push_back({x, cnt});
}
int dp[MAXN];

int calc() {
  int ans = 1;
  mx.clear();
  mn.clear();
  for (int i = 1; i <= k; ++i) {
    add_mn(a[i]);
    add_mx(a[i]);
    if (i > 1 && a[i] > a[i - 1])
      dp[i] = dp[i - 1] + (a[i] > a[i - 1]);
    else
      dp[i] = 1;
  }
  bool ok = (dp[k] >= k);
  for (int i = k + 1; i <= n; ++i) {
    add_mn(a[i]);
    add_mx(a[i]);
    if (a[i] > a[i - 1])
      dp[i] = dp[i - 1] + 1;
    else
      dp[i] = 1;
    if (a[i] == mx.front().first && a[i - k] == mn.front().first) {
      del_mn();
      del_mx();
      continue;
    }
    if (ok && dp[i] >= k) {
      del_mn();
      del_mx();
      continue;
    }
    ok |= (dp[i] >= k);
    ans++;
    del_mn();
    del_mx();
  }
  return ans;
}

int slow() {
  set<vector<int> > S;
  vector<int> cur;
  for (int i = 1; i <= n; ++i) {
    cur.push_back(a[i]);
  }
  for (int i = k; i <= n; ++i) {
    vector<int> init = cur;
    sort(init.begin() + i - k, init.begin() + i);
    S.insert(init);
  }
  return S.size();
}

int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);

#ifdef Local
  freopen(".in", "r", stdin);
#else
  // freopen("sum.in", "r", stdin);
  // freopen("sum.out", "w", stdout);
#endif
  srand(time(0));
  cin >> n >> k;

  for (int i = 1; i <= n; ++i) cin >> a[i];
  cout << calc();
  return 0;
  do {
    random_shuffle(a + 1, a + 1 + n);
    cerr << calc() << ' ' << slow() << endl;
  } while (calc() == slow());
  for (int i = 1; i <= n; ++i) {
    cerr << a[i] << ' ';
  }
  cerr << endl;
  return 0;
}

Measured memory_bytes: 8064
extern crate core;

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let output = run(input.trim().to_string());
    println!("{}", output);
}

fn run(input: String) -> String {
    let list = input.split_whitespace().skip(1).collect::<Vec<_>>();
    let mut a = Vec::with_capacity(list.len() / 2);
    let mut b = Vec::with_capacity(list.len() / 2);
    let mut top = list.len() % 2 != 0;
    for &x in &list {
        if top {
            a.push(x);
        } else {
            b.push(x);
        }
        top = !top;
    }
    a.reverse();
    a.append(&mut b);
    a.join(" ").to_string()
}

macro_rules! tests {
    ($($name:ident: $input:expr=>$output:expr,)*) => {
        mod tests {
            $(
                #[test]
                fn $name() {
                    assert_eq!(super::run($input.to_string()), $output.to_string());
                }
            )*
        }
    }
}

tests! {
    test1: "4
1 2 3 4" => "4 2 1 3",
    test2: "3
1 2 3" => "3 1 2",
    test3: "1
1000000000" => "1000000000",
    test4: "6
0 6 7 6 7 0" => "0 6 6 0 7 7",
}


Measured memory_bytes: 23280
# 両方の数列から同じ部分列がいくつあるか？
import numpy as np

MOD = 10**9+7
N, M = map(int, input().split())
S = input().split()
T = np.array(input().split(), dtype=np.int32)
dp = np.ones(M+1, dtype=np.int64)

for s in S:
  dp[1:] = ((dp[:-1] * (T == int(s))).cumsum() + dp[1:]) % MOD

print(dp[M])



Measured memory_bytes: 14536
#include <bits/stdc++.h>
#include <unordered_set>
using namespace std;
#define ll long long
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define repeat(i,s,n) for(int (i)=s; (i)<(n); (i)++)
#define revrep(i,n) for(int (i)=(n)-1;i>=0; i--)

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout<<setprecision(std::numeric_limits<float>::max_digits10);
  cout<<fixed;
  int n;
  cin>>n;
  vector<int> p(n);
  rep(i,n)cin>>p[i];
  bool f =true;
  rep(k,n-1) {
    if(p[k]<=p[k+1])
      f&=true;
    else
      f&=false;
  }
  if(f) {
    cout << "YES" << endl;
    return 0;
  }
  rep(i,n) {
    repeat(j,i+1,n) {
      swap(p[i],p[j]);
      bool f =true;
      rep(k,n-1) {
	if(p[k]<=p[k+1])
	  f&=true;
	else
	  f&=false;
      }
      if(f) {
	cout << "YES" << endl;
	return 0;
      }
      swap(p[i],p[j]);
    }
  }
  cout << "NO" << endl;
  return 0;
}


Measured memory_bytes: 256
//的場梨沙★担当
//結城晴★副担当
//日野茜★副担当
#include <vector>
#include <list>
#include <map>
#include <climits>
#include <set>
#include <unordered_set>
#include <unordered_map>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string.h>
#include <string>
#include <cstring>
#include <ctime>
#include <queue>
#include <random>
#include <cctype>
#include <complex>
#include <regex>
#include <unordered_map>
#include <string>
#include <algorithm>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <stdio.h>


using namespace std;

int main(void) {
    int K;
    cin>>K;
    cout<<(K/2)*((K+1)/2)<<endl;
}


Measured memory_bytes: 256
def mmok(i):
    return 1 <= i <= 12


S = input()
h = int(S[:2])
l = int(S[2:])

if mmok(h):
    if mmok(l):
        print('AMBIGUOUS')
    else:
        print('MMYY')
else:
    if mmok(l):
        print('YYMM')
    else:
        print('NA')


Measured memory_bytes: 2940
n , m = map(int, input().split(' '))
a = list()
b = list()

for row in range(n):
    a.append(list(map(int, input().split(' '))))
    
for ind in range(m):
    b.append(int(input()))

for row in range(n):
    ans = 0
    for col in range(m):
        ans += a[row][col] * b[col]
    print(ans)


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

ll N=1;

ll a,b,c,d;
ll cost;

void solve(ll sz){
	ll x1=a/sz,y1=b/sz,x2=c/sz,y2=d/sz;
	if(x1!=x2||y1!=y2){
		if(x1==x2&&x1%3==1&&abs(y1-y2)>1){
			ll A=a%sz,C=c%sz;
			cost=min(A+1+C+1,(sz-A)+(sz-C))+abs(b-d);
			return;
		}
		if(y1==y2&&y1%3==1&&abs(x1-x2)>1){
			ll B=b%sz,D=d%sz;
			cost=min(B+1+D+1,(sz-B)+(sz-D))+abs(a-c);
			return;
		}
	}
	if(sz>1)solve(sz/3);
}

int main(){
	rep(i,30)N*=3;
	int q;cin>>q;
	rep(i,q){
		cin>>a>>b>>c>>d;a--;b--;c--;d--;
		cost=abs(a-c)+abs(b-d);
		solve(N/3);
		printf("%lld\n",cost);
	}
}
/*
2
39 24 34 60
*/

Measured memory_bytes: 384
import numpy as np
nm = input()
n,m = nm.split()
n = int(n)
m = int(m)

xs = input()
xs = xs.split()
for i in range(m):
    xs[i] = int(xs[i])
xs = sorted(xs)

if (n>=m):
    print(0)
else:
    diff= []
    for i in range(m-1):
        diff.append(xs[i+1]-xs[i])
    s = np.argsort(diff)
    loop = 0
    total = sum(diff)
    if n == 1:
        print(total)
    else:
        for i in range(n-1):
            total -= diff[s[-(i+1)]]
        print(total)
      

Measured memory_bytes: 20720