akhauriyash/Code-Regression huggingface dataset:
H, W = map(int, input().split())
s = [[i for i in input()]for i in range(H)]
maze = [[False for i in range(W)] for i in range(H)]
bknum = 0
for i in range(H):
    for j in range(W):
        if s[i][j]==".":
            maze[i][j]=True
        else:
            maze[i][j]=False
            bknum += 1


def ncell(i, j):
    tmp = [[i-1,j],[i+1,j],[i,j-1],[i,j+1]]
    out = []
    for p in tmp:
        if 0<=p[0]<H and 0<=p[1]<W and maze[i][j]:
            out.append(p)
    return out

d = [[1000 for j in range(W)] for i in range(H)]
prev = [[-1 for j in range(W)] for i in range(H)]
d[0][0]=0
Q = set()
for i in range(H):
    for j in range(W):
        if maze[i][j]:
            Q.add(i*W+j)
while(len(Q)!=0):
    u = list(Q)[0]
    du = d[u//W][u%W]
    for v in Q:
        if d[v//W][v%W]<du:
            du = d[v//W][v%W]
            u=v
    Q -=set([u])
    for v in ncell(u//W, u%W):
        if d[v[0]][v[1]]>d[u//W][u%W]+1:
            d[v[0]][v[1]]=d[u//W][u%W]+1
            prev[v[0]][v[1]]=u
length=d[H-1][W-1]
if length != 1000:
    print(H*W-length-1-bknum)
else:
    print(-1)


Measured memory_bytes: 3444
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <limits>

typedef long long int64;


struct pred {
  bool operator()(std::pair<int, int>& rhs, std::pair<int, int>& lhs) {
    return rhs.second < lhs.second;
  }
};

int main(void) {
  int n;
  std::cin >> n;
  std::vector<std::pair<int, int> > tbl;

  for (int i = 0; i < n; i++) {
    std::pair<int, int> el;
    el.first = i + 1;
    std::cin >> el.second;
    tbl.push_back(el);
  }
  std::sort(tbl.begin(), tbl.end(), pred());
  for (auto el : tbl) {
    std::cout << el.first << " ";
  }
  std::cout << std::endl;
  return 0;
}


Measured memory_bytes: 1780
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<utility>
#include<tuple>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>

using namespace std;

using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;

#define BIL ((ll)1e9)
#define MOD ((ll)1e9+7)
#define INF (1LL<<60)           //1LL<<63でオーバーフロー
#define inf (1<<29)             //1<<29でオーバーフロー

int main(int argc,char* argv[]){
    ll h,w;
    cin >> h >> w;

    if(h==1 || w==1){
        cout << 1 << endl;
        return 0;
    }

    ll ans;
    if(h%2==0){
        ans=w*(h/2);
    }else{
        if(w%2==0){
            ans=w*(h/2)+(w/2);
        }else{
            ans=w*(h/2)+(w/2)+1;
        }
    }

    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 3604
#include<iostream>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
int main()
{
	string s;
	cin>>s;
	int a=0,b=0;
	for(int i=0;i<s.size();i++)
	{
		if(s[i]=='A')
		{
			a++;
		}
		if(s[i]=='B')
		{
			b++;
		}
	}
	if(a==2||b==2)
	{
		cout<<"Yes"<<endl;
	}
	else
	{
		cout<<"No"<<endl;
	}
}

Measured memory_bytes: 256
#include<stdio.h>

int main() {
   int x,y;
   scanf("%d", &x);
   scanf("%d", &y);
int ans;
  ans = 2*x -1;
  if(ans<2*y -1)ans = 2*y -1;
  if(ans<x+y)ans = x+y;
   printf("%d",ans);
}


Measured memory_bytes: 128
main(){
    int i=0;
    int j=0;
    
    int t[9<<14]={};
    int m=0;
    int s=0;
    
    for(;~scanf("%d",&t[i]);i++){
        i*(t[i]>m)?m=t[i]:0;
    }
    for(;++j<t[0]+2;){
        abs(t[j]-m/2)<abs(s-m/2)?s=t[j]:0;
    }
    printf("%d %d",m,s);
}

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

int main() {
  int a,b;cin>>a>>b;
  if (a==1) a = 14;
  if (b==1) b = 14;
  if (a > b) cout << "Alice";
  else if (a < b) cout << "Bob";
  else cout<<"Draw";
}


Measured memory_bytes: 256
#include<stdio.h>
int main()
{
	char n[4];
	scanf("%s",n);
	for(int i=0;i<3;i++){
		if(n[i]=='7'){
			printf("Yes\n");
			break;
		}
		else if(i==2)
		printf("No\n");
	}
	return 0;
}
	

Measured memory_bytes: 1620
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
#define MOD 1000000007
#define INF (1e9)
#define PI (acos(-1))
#define print(x) cout << x << endl
#define yes cout << "Yes" << endl
#define YES cout << "YES" << endl
#define no cout << "No" << endl
#define NO cout << "NO" << endl

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

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

template<class T> inline auto __lcm(T& a, T& b) 
{ return a * b / __gcd(a, b); }

template<typename T> void remove(std::vector<T>& vector, unsigned int index)
{ vector.erase(vector.begin() + index); }

ll arysum(ll n) {
  return n * (n+1) / 2;
}

int main() {
  string S;  cin >> S;
  vector<ll> larger;
  vector<ll> smaller(S.size(), 0);
  
  ll lcnt = 0;
  ll scnt = 0;
  rep(i, S.size()) {
    if (S[i] == '<') {
      lcnt++;
      scnt = 0;
      larger.push_back(lcnt);
    } else {
      lcnt = 0;
      larger.push_back(0);
    }
  }
  lcnt = 0;
  scnt = 0;
  rep(i, S.size()) {
    if (S[S.size()-i-1] == '>') {
      scnt++;
      lcnt = 0;
      smaller[S.size()-i-1] = scnt;
    } else {
      scnt = 0;
    }
  }
  

  ll res = 0;
  rep(i, S.size()-1) {
    if (S[i] == '<' && S[i+1] == '>') {
      ll M = max(larger[i], smaller[i+1]);
      if (M == larger[i]) {
        res += arysum(larger[i]) + arysum(smaller[i+1]-1);
      } else {
        res += arysum(larger[i]-1) + arysum(smaller[i+1]);
      }
      //print("l:" << larger[i] << ", s:" << smaller[i+1] << ", res:" << res);
    }
  }
  if (S[0] == '>') {
    res += arysum(smaller[0]);
  }
  if (S[S.size()-1] == '<') {
    res += arysum(larger[S.size()-1]);
  }

  print(res);
  rep(i, S.size()) {
    //print("l:" << larger[i] << ", s:" << smaller[i]);
  }

  return 0;
}


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

int main(){
  int n;
  cin>>n;
  int p=0,q=0,r=0;
  rep(i,0,n){
    int a;
    cin>>a;
    if(a%2!=0){
      p++;
    }
    else if(a%4==0){
      r++;
    }
    else{
      q++;
    }
  }
  if(p<=r) cout<<"Yes"<<endl;
  else if(p==r+1 && q==0) cout<<"Yes"<<endl;
  else cout<<"No"<<endl;
}

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

int main(){
    int N,i,ans;
    cin >> N;
    vector<int> L(2*N);
    for(i=0;i<2*N;i++) cin >> L.at(i);
    sort(L.begin(),L.end());
    ans = 0;
    for(i=0;i<N;i++) ans += L.at(2*i);
    cout << ans << endl;
    return 0;
}

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

int main() {
  ll r;

  cin >> r;
  cout << fixed << setprecision(10);
  cout << 2*r*3.14159265358979 << endl;
  return 0;
}

Measured memory_bytes: 3764
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define MAXN 3 * 100005

int n, a[MAXN], dp[2][MAXN], m0, m1, ans = 1000000009;

signed main(){
    cin >> n;
    for(int i = 0; i < n; i++){
        char d;
        cin >> d;
        dp[0][i + 1] = dp[0][i];
        dp[1][i + 1] = dp[1][i];
        if(d == 'W'){
            a[i] = 0;
            dp[0][i + 1] = dp[0][i] + 1;
        }
        else{
            a[i] = 1;
            dp[1][i + 1] = dp[1][i] + 1;
        }
        //printf("dp[0][%lld] %lld\ndp[1][%lld] %lld\n", i + 1, dp[0][i + 1], i + 1, dp[1][i + 1]);
    }
    m0 = dp[0][n];
    m1 = dp[1][n];
    for(int i = 0; i < n; i++){
        if(i == 0){
            ans = ans < m1 - dp[1][1] ? ans : m1 - dp[1][1];
        }
        else if(i == n - 1){
            ans = ans < dp[0][i] ? ans : dp[0][i];
        }
        else{
            ans = ans < dp[0][i] + (m1 - dp[1][i + 1]) ? ans : dp[0][i] + (m1 - dp[1][i + 1]);
        }
        //printf("%lld ans %lld\n", i + 1, ans);
    }
    cout << ans << endl;

    return 0;
}



Measured memory_bytes: 7296
// H - Grid 1
#include <bits/stdc++.h>
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
#define rep(i,n) for(int i=0;i<(n);++i)
#define MOD 1000000007

int main(){
	int H,W; cin>>H>>W;

	vector<string> maze(H);
	rep(h, H) cin>>maze[h];

	vvi dp(H, vi(W, 0)); // (h,w): count
	queue<pair<int,int>> q; // <h,w>
	dp[0][0] = 1;
	q.push({0,0});

	while(q.size()){
		int h,w; tie(h,w) = q.front(); q.pop();

		// right (h,w+1)=(h,w)+(h-1,w+1)
		if(w+1 < W
		&& maze[h][w+1] == '.'
		&& dp[h][w+1] <= 0){
			dp[h][w+1] = dp[h][w];
			if(0 <= h-1) dp[h][w+1] += dp[h-1][w+1];
			dp[h][w+1] %= MOD;
			q.push({h,w+1});
		}

		// down (h+1,w)=(h,w)+(h+1,w-1)
		if(h+1 < H
		&& maze[h+1][w] == '.'
		&& dp[h+1][w] <= 0){
			dp[h+1][w] = dp[h][w];
			if(0 <= w-1) dp[h+1][w] += dp[h+1][w-1];
			dp[h+1][w] %= MOD;
			q.push({h+1,w});
		}

	}
	cout<< dp[H-1][W-1] <<endl;

	// // print ==========================
	// puts("===");//
	// cout<<"H "<<H<<" W "<<W<<"\n";//
	// rep(h,H) cout<<maze[h]<<"\n";//
	// for(auto v:dp){
	// 	for(auto x:v)printf(" %2d",x);
	// 	puts("");
	// }
	// // =================================

}


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

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)

using ll = long long;
using ld = long double;
ll INF = LLONG_MAX;

using vi = vector<int>;
using vll = vector<ll>;
using pii = pair<int, int>;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }
	
	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);
	
	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) { 
		pr(t); pr(ts...); 
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) { 
		pr("{",x.f,", ",x.s,"}"); 
	}
	template<class T> void pr(const T& x) { 
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0; 
		pr("}");
	}
	
	void print() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void print(const T& t, const Ts&... ts) { 
		pr(t); if (sizeof...(ts)) pr(" "); print(ts...); 
	}
}

using namespace output;

const int MAXN = 1e5 + 10;
ll MOD = 1e9+7;
vll fact (MAXN);
vll invfact (MAXN);
vll pow2(MAXN);
vll inv (MAXN);

ll binpow(ll a, ll b) {
    ll res = 1;
    while (b > 0) {
        if (b & 1)
            res = res * a;
        res %= MOD;
        a = a * a;
        a %= MOD;
        b >>= 1;
    }
    return res;
}

ll choose(ll n, ll k) {
    return fact[n] * invfact[k] % MOD * invfact[n-k] % MOD;
}

ll formula(ll r) {
	ll total = 0;
	for (int i = 1; i <= r; ++i) {
		total += choose(r, i) * fact[i];
	}
	return total;
}

ll formula2(ll r) {
	return fact[r] * r;
}

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	
	fact[0] = 1;
    FOR(i, 1, MAXN) fact[i] = fact[i-1] * i % MOD;

	int  N; cin >> N;
	vll arr (N);
	F0R(i, N) cin >> arr[i];

	vll BS (N);
	F0R(i, N) BS[i] = binpow(i + 1, MOD - 2);

	vll cum (N);
	FOR(i, 1, N) cum[i] = (cum[i-1] + BS[i]) % MOD;

	ll ans = 0;
	F0R(i, N) {
		ll prob = 1 + cum[i] + cum[N-i-1];
		ans = (ans + arr[i] * prob) % MOD;
	}
	
	print(ans * fact[N] % MOD);
}

Measured memory_bytes: 5760
import java.util.Scanner;
import java.util.stream.Collectors;

class Main {

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

    void compute() {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        int K = sc.nextInt();
        for (int i = 0; i <= N; i++) {
            for (int j = 0; j <= M; j++) {
                if (i * M + j * N - 2 * i * j == K) {
                    System.out.println("Yes");
                    return;
                }
            }
        }
        System.out.println("No");
    }
}


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

int n, m;
int X, Y, Z;
struct node{
	ll x, y, z;
}p[1005];
ll ans;

bool cmp(const node &a, const node &b){
	return a.x * X + a.y * Y + a.z * Z > b.x * X + b.y * Y + b.z * Z;
}

int main(){
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= n; i++) scanf("%lld%lld%lld", &p[i].x, &p[i].y, &p[i].z);
	
	for(X = -1; X <= 1; X += 2){
		for(Y = -1; Y <= 1; Y += 2){
			for(Z = -1; Z <= 1; Z +=2){
				sort(p + 1, p + 1 + n, cmp);
				ll now = 0;
				for(int i = 1; i <= m; i++) now += X * p[i].x + Y * p[i].y + Z * p[i].z;
				ans = max(ans, now);
			}
		}
	}
	printf("%lld\n", ans);
	return 0;
}

Measured memory_bytes: 3796
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define repp(i,l,r,k)for(ll i=(l);i<(r);i+=(k))
#define INF ((1LL<<62)-(1LL<<31))
#define max(p,q)((p)>(q)?(p):(q))
#define min(p,q)((p)<(q)?(p):(q))
#define bit(n,m)(((n)>>(m))&1)
int upll(const void*a, const void*b){return*(ll*)a<*(ll*)b?-1:*(ll*)a>*(ll*)b?1:0;}
int downll(const void*a, const void*b){return*(ll*)a<*(ll*)b?1:*(ll*)a>*(ll*)b?-1:0;}
void sortup(ll*a,int n){qsort(a,n,sizeof(ll),upll);}
void sortdown(ll*a,int n){qsort(a,n,sizeof(ll),downll);}
ll pom(ll a,ll n,int m){ll x=1;for(a%=m;n;n/=2)n&1?x=x*a%m:0,a=a*a%m;return x;}
//#define MOD 998244353
#define MOD 1000000007
#define invp(a,p)pom(a,p-2,p)

//辺の情報を個別に持つタイプ
typedef struct edge{ll s,g;}E;
typedef struct graph{
	ll vcnt,ecnt;
	E  e[400010];//適宜変える
	ll id[200010];//適宜変える
}G;
 
int esort(const void*a,const void*b){
	E*p=(E*)a,*q=(E*)b;
	if((*p).s<(*q).s)return -1;
	if((*p).s>(*q).s)return  1;
	if((*p).g<(*q).g)return -1;
	return 1;
}
 
G g;
void readgraph(){
	//適宜変える
	ll n;
	scanf("%lld",&n);
	rep(i,0,n-1){
		ll x,y;
		scanf("%lld%lld",&x,&y);
		x--,y--;
		g.e[2*i].s=x;
		g.e[2*i].g=y;
		g.e[2*i+1].s=y;
		g.e[2*i+1].g=x;
	}
	g.vcnt=n;
	g.ecnt=2*n-2;
	qsort(g.e,g.ecnt,sizeof(E),esort);
 
	int p=0;
	rep(i,0,g.vcnt){
		while(p<g.ecnt&&g.e[p].s<i)p++;
		g.id[i]=p;
	}
	g.id[g.vcnt]=g.ecnt;//一応番兵
}

ll temp[200010];

ll dfs(ll s){
	for(int i=g.id[s];i<g.id[s+1];i++){
		if(temp[g.e[i].g]==0){
			temp[g.e[i].g]=temp[s]+1;
			dfs(g.e[i].g);
		}
	}
}

int main(){
	readgraph();
	temp[0]=1;
	dfs(0);
	ll M=0,Mi;
	rep(i,0,g.vcnt){
		if(temp[i]>M){
		M=temp[i];
		Mi=i;
		}
	}
	rep(i,0,g.vcnt)temp[i]=0;
	temp[Mi]=1;
	dfs(Mi);
	rep(i,0,g.vcnt)if(temp[i]>M){
		M=temp[i];
		Mi=i;
	}
//	printf("%d ",M);
	puts(M%3==2?"Second":"First");
}

Measured memory_bytes: 18960
#include<bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define all(x)(x).begin(), (x).end() // 昇順ソート
#define rall(v)(v).rbegin(), (v).rend() // 降順ソート
#define INF 1LL << 60
typedef long long int LL;
typedef long long int ll;
#define pll pair < ll, ll >
#define F first
#define S second
const int MOD = 1000000007;
template < class T > bool chmax(T & a,const T & b) { if (a < b) { a = b; return true; } return false; }
template < class T > bool chmin(T & a,const T & b) { if (a > b) { a = b; return true; } return false; }
// 任意のlogは　対数の底の変換を使う    log(N) / log(任意の底)

int main() {
    int N,K;cin >> N >> K;
    vector<int> d(K);
    vector<vector<int>> A(K);
    rep(i,K){
        cin >> d[i];
        rep(j,d[i]){
            int tmp;cin >> tmp;
            A[i].push_back(tmp);
        }
    }

    map<int,int> m;
    rep(i,K){
        for(auto t : A[i]){
            m[t]++;
        }
    }

    cout << N - m.size() << endl;
}

Measured memory_bytes: 3660
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip> 
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <bitset>

using namespace std;


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

	long long n, i, j, k, t;
	cin >> n;
	vector<long long> c(n), s(n), f(n), ans(n, 0);
	for (i = 0; i < n - 1; i++) cin >> c[i] >> s[i] >> f[i];

	for (i = 0; i < n - 1; i++) {
		t = 0;
		for (j = i; j < n - 1; j++) {
			if (t <= s[j]) t = s[j];
			else t = (t + f[j] - 1) / f[j] * f[j];
			t += c[j];
		}
		ans[i] = t;
	}
	for (i = 0; i < n; i++) cout << ans[i] << "\n";


	return 0;
}



Measured memory_bytes: 256
import sys
s = sys.stdin.readlines()
N,M,Q = map(int,s[0].split())

Section = [[0]*N for _ in range(N)]
for L,R in (map(int, e.split()) for e in s[1:M+1]):
    Section[L-1][R-1] += 1

Sum = [[0]*(N+1) for _ in range(N+1)]
for i in range(N):
    for j in range(N):
        Sum[i+1][j+1] = Sum[i][j+1]+Sum[i+1][j]-Sum[i][j]+Section[i][j]

Ans = [[0]*N for _ in range(N)]
for i in range(N):
    for j in range(i,N):
        Ans[i][j] = Sum[j+1][j+1]-Sum[i][j+1]

for p,q in (map(int, e.split()) for e in s[M+1:]):
    print(Ans[p-1][q-1])

Measured memory_bytes: 42496
use proconio::{fastout, input};
use std::io::*;
use std::str::FromStr;

use std::cmp::{max, min};

use std::collections::VecDeque;

fn main() {
    input! {
        n: usize,
        a: [i64; n],
    }
    let mut cnt = 0;
    let mut q: VecDeque<i64> = VecDeque::new();

    for i in (0..n).rev() {
        let ai = a[i];
        let idx = q.upper_bound(ai);
        if q.len() == idx {
            q.push_back(ai);
            cnt += 1;
        } else {
            q[idx] = ai;
        }
        // println!("q:{:?}", q);
    }
    println!("{}", cnt);
}

use std::cmp::Ordering;

pub trait BinarySearch<T> {
    fn lower_bound(&self, x: T) -> usize;
    fn upper_bound(&self, x: T) -> usize;
}

impl<T: Ord> BinarySearch<T> for VecDeque<T> {
    fn lower_bound(&self, x: T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(&x) {
                Ordering::Less => {
                    low = mid + 1;
                }
                Ordering::Equal | Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
    fn upper_bound(&self, x: T) -> usize {
        let mut low = 0;
        let mut high = self.len();

        while low != high {
            let mid = (low + high) / 2;
            match self[mid].cmp(&x) {
                Ordering::Less | Ordering::Equal => {
                    low = mid + 1;
                }
                Ordering::Greater => {
                    high = mid;
                }
            }
        }
        low
    }
}


Measured memory_bytes: 4808
#include <bits/stdc++.h>
using i64 = long long;

int main() {
    int n;
    std::cin >> n;

    std::vector<std::vector<i64>> cnt(10, std::vector<i64>(10));
    for (int k = 1; k <= n; k++) {
        auto s = std::to_string(k);
        int i = s.front() - '0', j = s.back() - '0';
        cnt[i][j]++;
    }

    i64 ret = 0;
    for (int i = 1; i <= 9; i++) for (int j = 1; j <= 9; j++) {
        ret += cnt[i][j] * cnt[j][i];
    }

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

    return 0;
}


Measured memory_bytes: 256
import std.stdio;
import std.algorithm;
import std.string;
import std.range;
import std.array;
import std.conv;
import std.complex;
import std.math;
import std.ascii;
import std.bigint;
import std.container;

void main() {
	int h,w;
	int[] hw = array(map!(a => to!int(a))(readln().strip().split()));
	h = hw[0];
	w = hw[1];
	while((h|w) != 0) {
		auto s = new string[](h);
		foreach(i;0..h){
			s[i] = readln().strip();
		}
		auto dp = new int[][](h+1,w+1);
		foreach(i; 0..h) {
			foreach(j; 0..w) {
				if(s[i][j] == '.')
					dp[i+1][j+1] = dp[i+1][j]+1;
				else
					dp[i+1][j+1] = 0;
			}
		}
		int ans = 0;
		foreach(i; 0..h) {
			foreach(j; 0..w) {
				int maxS = 0;
				int minw = int.max;
				foreach_reverse(k; 0..i+1) {
					minw = min(minw, dp[k+1][j+1]);
					if(minw == 0)
						break;
					maxS = max(maxS, (i-k+1)*minw);
				}
				ans = max(ans, maxS);
			}
		}
		writeln(ans);

		hw = array(map!(a => to!int(a))(readln().strip().split()));
		h = hw[0];
		w = hw[1];
	}
}

Measured memory_bytes: 3632
#include <vector>
#include <queue>
#include <algorithm>
#include <iostream>
#include <string>
#include <ctime>
#include <map>
#include <stack>
#include <sstream>
#include <set>
#include <cmath>
#include <functional>
#include <numeric>

using namespace std;

int n;
int color[100001];
vector <int> adj[100001];
int depth[2][100001];
const int INF = 210000000;
void bfs()
{

	queue <int> que;

	//init
	for (int i = 1; i <= n; i++)
	{
		depth[0][i] = INF;
		depth[1][i] = INF;
	}
	//first fennce
	que.push(1);
	depth[0][1] = 0;

	while (!que.empty())
	{
		int a = que.front();
		que.pop();

		for (int i = 0; i < adj[a].size(); i++)
		{
			if (depth[0][adj[a][i]] == INF)
			{
				depth[0][adj[a][i]] = depth[0][a] + 1;
				que.push(adj[a][i]);
			}
		}
	}

	//second
	que.push(n);
	depth[1][n] = 0;

	while (!que.empty())
	{
		int a = que.front();
		que.pop();

		for (int i = 0; i < adj[a].size(); i++)
		{
			if (depth[1][adj[a][i]] == INF)
			{
				depth[1][adj[a][i]] = depth[1][a] + 1;
				que.push(adj[a][i]);
			}
		}
	}
}
int main()
{
	int a, b;
	int f = 0, s = 0;
	cin >> n;

	for (int i = 0; i < n - 1; i++)
	{
		cin >> a >> b;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}

	bfs();

	for (int i = 1; i <= n; i++)
	{
		if (depth[0][i] <= depth[1][i])
		{
			f++;
		}
		else
		{
			s++;
		}
	}

	if (f > s)
	{
		cout << "Fennec" << endl;
	}
	else
	{
		cout << "Snuke" << endl;
	}
	return 0;
}

Measured memory_bytes: 6656
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
inline int read() {
	int x=0;char c=getchar();
	while (c<'0'||c>'9') c=getchar();
	while (c>='0'&&c<='9') x=x*10+c-'0',c=getchar();
	return x;
}
int main() {
	printf("%d\n",read()*read());
	return 0;
}

Measured memory_bytes: 3784
#include<stdio.h>
#include<string.h>
  char ga[1<<21],k[256];

int main(int argc,char *argv[]){
  int flg, val,s,t;
  char c;
  k['T'] = 1;
  k['G'] = 2;
  k['C'] = 3;
  k['A'] = 4;
   
  scanf("%d", &val);
  getchar();
  while (val--) {
    s = 0;
    t = 1;
    flg = ( c = getchar() ) == 'i';
    while ( ( c = getchar() ) != ' ' );
    while ( ( c = k[getchar()] ) != 0 ) {
      s += c * t;
      t *= 4;
    }
    if (flg) ga[s] = 1; else puts( ga[s] ? "yes" : "no" );
  }
  return 0;
}



Measured memory_bytes: 3020
# coding: utf-8
# Your code here!
A,B,C,D,E,F=map(int,input().split())

A=A*100
B=B*100

ans=[]
water=set()

for i in range(F//(A)+1):
    for j in range((F-A*i)//B+1):
        water.add(A*i+B*j)
water.remove(0)

ans=-1
ans_all=-1
ans_sol=-1

for item in water:
    for i in range((F-item)//(C)+1):
        if C*i/item*100>E:
            break
        j=min((F-item-C*i)//D,(item*E/100-C*i)//D)
        if (C*i+D*j)/(item+C*i+D*j)>ans:
            ans_sol=C*i+D*j
            ans_all=item+ans_sol
            ans=ans_sol/ans_all
    
print(int(ans_all),int(ans_sol))


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

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

#define rep(i,n) for(i = 1; i <= n; ++i) 
#define REP(i,k,n) for(int i = k; i <= n; ++i) 
#define REPR(i,k,n) for(int i = k; i >= n; --i)
#define mp make_pair

const int maxe = 2e5+5;
ll t=1;
ll n, k;
ll nextblock[maxe];
ll score[maxe];
void solve(){
	cin >> n >> k;
	int i;
	rep(i,n){
		cin >> nextblock[i];
	}
	rep(i,n){
		cin >> score[i];
	}
	ll ans=-5e15;
	rep(i,n){
		ll cyclesize=0;
		ll cyclescore=0;
		int currsquare = i;
		do{
			currsquare = nextblock[currsquare];
			cyclescore += score[currsquare];
			cyclesize++;
			
		} while(currsquare != i);
		ll maxsc = -5e15;
		ll temp = 0;
		currsquare = i;
		ll kcopy = k;
		if(k < cyclesize){
			while(kcopy){
				currsquare = nextblock[currsquare];
				temp += score[currsquare];
				maxsc = max(temp, maxsc);
				kcopy--;
			}
		}
		else{
			ll w=cyclesize;
			while(w){
				currsquare = nextblock[currsquare];
				temp += score[currsquare];
				maxsc = max(temp, maxsc);
				w--;
			}
			if(cyclescore > 0){
				ll rem = k%cyclesize;
				currsquare = i;
				ll x = -5e15;
				ll y = 0;
				while (rem){
					currsquare = nextblock[currsquare];
					y += score[currsquare];
					x = max(x, y);
					rem--;
				}
				ll noofcycles = k/cyclesize;
				ll maxscinonecycle = maxsc;
				maxsc = max(noofcycles*cyclescore+x, (noofcycles-1)*cyclescore+maxscinonecycle);
			}
		}
		ans = max(ans, maxsc);
	}
	cout << ans;
}

int main(){
	while(t--){
		solve();
	}
	return 0;
}





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

int main() {
  ll n;
  cin >> n;
  map<int,int> a;
  for(ll i=2;i<=pow(n,0.5);i++){
    if(n%i!=0)
      continue;
    while(n%i==0){
        a[i]++;
        n=n/i;
    }
  }
  if(n!=1)
    a[n]++;
  int count=0;
  for (auto p : a) {
    auto k = p.first;
    auto v = p.second;
    int i=1;
    while(v-i>=0){
      v=v-i;
      i++;
      count++;
    }
  }
  cout << count << endl;
}



Measured memory_bytes: 4012
import math


import math
import numpy as np
from collections import deque
def sieve_of_erastosthenes(num):
    """
    エラストネスの篩
    :param num:
    :return:
    """
    input_list = [False if i % 2 == 0 or i % 3 == 0 or i % 5 == 0 else True for i in range(num)]
    input_list[0] = input_list[1] = False

    input_list[2] = input_list[3] = input_list[5] = True
    sqrt = math.sqrt(num)

    for serial in range(3, num, 2):

        if serial >= sqrt:
            return input_list

        for s in range(serial ** 2, num, serial):
            input_list[s] = False
    return input_list

N=int(input())

def factorization(n):
    """

    素因数分解
    :param n:
    :return:
    """
    arr = {}
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr[i]= cnt

    if temp!=1:
        arr[temp]= 1

    if arr=={}:
        arr[n]= 1

    return arr

def make_divisors(n):
    lower_divisors , upper_divisors = [], []
    i = 1
    while i*i <= n:
        if n % i == 0:
            lower_divisors.append(i)
            if i != n // i:
                upper_divisors.append(n//i)
        i += 1
    return lower_divisors + upper_divisors[::-1]

input_ = make_divisors(N)
cnt = 0
# for i in input_:
#     n = N
#     _cnt =1
#     stack = deque([i])
#     seen= [i]
#     while stack:
#         s =stack.pop()
#         hoge= stack[-1]
#         for s
#         if math.log(hoge,)  and not hoge in seen:
#             stack.append(n/i)
#         else:
#             stack.pop
# prime_list = np.array(range(1,N+1))[sieve_of_erastosthenes(N)]
if N ==1:
    print(0)
    exit()
prime_dict = factorization(N)
# print(prime_dict)
searched = []
count=0
for prime, val in prime_dict.items():
    for e in range(1 ,val+1):

        z = prime ** e

        if N%z == 0 and not z in searched:
            searched.append(z)
            N = N//z
            count += 1
print(count)




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


int main()
{
    int n,m,sum=0;
    cin>>n>>m;
    for(int i=n-1;i>=0;i--){
        sum=sum+i;
    }
    for(int i=m-1;i>=0;i--){
        sum=sum+i;
    }
    cout<<sum;
}


Measured memory_bytes: 256
import java.util.Scanner;

public class Main {

    private static Scanner sc = new Scanner(System.in);

    public static void main(String args[]) {

        long ppl = sc.nextLong();
        long[] time = new long[5];
        for (int i=0; i < 5; i++)
            time[i] = sc.nextLong();

        int minIndex = minIndex(time);
        long slowestPass = ppl / time[minIndex] + (ppl % time[minIndex] == 0 ? 0 : 1);

        System.out.println(slowestPass + 4);

    }

    private static int minIndex(long[] list) {
        int index = 0;
        long min = Long.MAX_VALUE;
        for (int i=0; i < list.length; i++) {
            if (list[i] < min) {
                index = i;
                min = list[i];
            }
        }
        return index;
    }

}


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

typedef struct
{
	int x, y;
}pos_t;

#define N_MAX 50
#define M_MAX 50

int main(void)
{
	int N, M, i, j;
	pos_t student[N_MAX];
	pos_t check[M_MAX];
	int distance, distance_min, index;

	while(scanf("%d%d", &N, &M)==2)
	{
		for(i=0;i<N;i++)
		{
			scanf("%d%d", &student[i].x, &student[i].y);
		}
		for(i=0;i<M;i++)
		{
			scanf("%d%d", &check[i].x, &check[i].y);
		}

		for(i=0;i<N;i++)
		{
			for(j=0;j<M;j++)
			{
				distance=abs(student[i].x-check[j].x)+abs(student[i].y-check[j].y);
				if(j==0 || distance_min>distance)
				{
					distance_min=distance;
					index=j+1;
				}
			}
			printf("%d\n", index);
		}
	}

	return 0;
}


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

#include <iostream>
#include <fstream>

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

using namespace std;

typedef unsigned long long ll;
typedef int                     integer;
#define int                     long long
#define ii                      pair<int,int>
#define vii                     vector<pair<int,int>>
#define vi                      vector<int>
#define vvi                     vector<vector<int>>
#define f(a,b,c)                for(int a=(b);a<(c);a++)
#define s(x)                    in>>x
#define s2(x,y)                 in>>x>>y
#define s3(x,y,z)               in>>x>>y>>z
#define s4(x,y,z,w)             in>>x>>y>>z>>w
#define p(x)                    out<<(x)<<endl
#define p2(x,y)                 out<<(x)<<" "<<(y)<<endl
#define pl(x)                   out<<(x)
#define p2l(x,y)                out<<(x)<<" "<<(y)
#define p1d(a,n)                for(int ix=0;ix<(n);ix++) out<<a[ix]<<" "; out<<endl
#define p2d(a,n,m)              for(int ix=0;ix<(n);ix++){ for(int jx=0;jx<(m);jx++) out<<a[ix][jx]<<" "; out<<endl;}
#define range(v)                v.begin(),v.end()
#define w(x)                    while(x--)
#define rst(x)                  memset(x, -1, sizeof(x))

void ssolve(std::istream& in, std::ostream& out){
    string s, t;
    s2(s,t);


    int best = LLONG_MAX;
    f(i,0,s.size()-t.size()+1) {
        int c = 0;
        f(j,0,t.size()) {
            if(t[j] != s[i+j]) c++;
        }
        best = min(c, best);
    }

    out<<best<<endl;
}

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


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


Measured memory_bytes: 3584
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define EPS 1e-9
#define mp make_pair
#define x first
#define y second
const double PI = acos(-1);

typedef pair<int, int> pii;
const int N = 200010;
const ll oo = 5e18;

int n;
ll X, x[N], f[N], pre[N];

int main() {
	cin >> n >> X;
	for (int i = 1; i <= n; ++i) {
		scanf("%lld", &x[i]);
		pre[i] = x[i] + pre[i - 1];
	}
	f[0] = f[1] = 5;
	for (int i = 2 ; i <= n ; ++i)
		f[i] = f[i - 1] + 2;
	ll res = oo;
	double mx = oo;
	for (int k = 1; k <= n; ++k) {
		int cur = n, idx = 0;
		ll fn = X * (n + k);
		long double me = X * (n + k);
		while (cur >= 1) {
			ll sum = pre[cur] - pre[max(0, cur - k)];
			me += sum * f[idx];
			if(me > oo)break;
			fn += sum * f[idx++];
			cur -= k;
		}
		if(me <= mx)res = min(res,fn);
	}
	cout << res << endl;
	return 0;
}

Measured memory_bytes: 4992
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
 





import static java.util.Comparator.*;
 
public class Main {
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        Solver solver = new Solver(System.in, out);
        solver.solve();
//        solver.test();
        out.close();
    }
}
class Solver {
	Scanner sc;
	PrintWriter out;
    public Solver(InputStream in, PrintWriter out) {
    	sc = new Scanner(in);
    	this.out = out;
    }
    //================================================================================
    public void solve() {
    	String S = sc.next();
    	String T = sc.next();
    	out.println(T + S);
    }
}

Measured memory_bytes: 20692
X = int(input())

if X > 1:
    line = input()
    v_inputs = [int(n) for n in line.split()]

    line = input()
    numbers = [int(n) for n in line.split()]
else:
    v_inputs = [int(input())]
    numbers = [int(input())]

cost_values = [
                gem_value - gem_cost
                for gem_value, gem_cost in zip(v_inputs, numbers)]
predicted_value = 0
for cost_value in cost_values:
    if cost_value > 0:
        predicted_value += cost_value

print(predicted_value)


Measured memory_bytes: 3064
n=input()
n=int(n)
arrstr=input()
ans=0
for no in range(1000):
    no=str(no);
    no=no.zfill(3)
    suc=0
    poi=0
    for i in range(len(arrstr)):
        if(arrstr[i]==no[poi]):
            poi+=1
            if poi==3:
                suc=1
                break
             
    if suc:ans+=1
print(ans)

Measured memory_bytes: 40940
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

int main(void) {
  int W;
  cin >> W;
  cout << W * 32 << endl;
  return 0;
}



Measured memory_bytes: 3096
n, t = map(int, input().split())
l = list(map(int, input().split()))
now = 0
latest = 0
ans = 0

for i in l:
    now = i
    #print(now,latest,t)
    if now-latest >= t:
        ans += t
    else:
        ans += now-latest
    
    latest = now
ans += t
print(ans)


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

signed main() {
  int N, K;
  cin >> N >> K;
  
  vector<int> X(N);
  for( int i = 0; i < N; i++ ) cin >> X.at(i);
  
  int l = 0;
  int r = K-1;
  int ans = 100000000000000;
  for( int i = 0; r+i < N; i++ ){
    int kyori = min( abs(X.at(l+i)) + abs( X.at(r+i)-X.at(l+i) ), abs(X.at(r+i)) + abs( X.at(l+i)-X.at(r+i) ) );
    ans = min(ans, kyori);
  }
  cout << ans << endl;

}

Measured memory_bytes: 1024
#include <iostream>
#include <iomanip>
#include <cmath>
#include <functional>
#include <algorithm>
#include <numeric>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <boost/range/irange.hpp>
#include <boost/container/static_vector.hpp>
#include <boost/utility/string_ref.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/math/common_factor_rt.hpp>

template <class... Args>
struct tuple_input_impl;
template <std::size_t i, std::size_t... tail>
struct tuple_input_impl<std::index_sequence<i, tail...>>
{
    template <class... Args>
    static void f(std::tuple<Args...>& x)
    {
        std::cin >> std::get<i>(x);
        tuple_input_impl<std::index_sequence<tail...>>::f(x);
    }
};
template <>
struct tuple_input_impl<std::index_sequence<>>
{
    static void f(...) {}
};

template <class... Args>
std::istream& operator>>(std::istream& in, std::tuple<Args...>& x)
{
    tuple_input_impl<std::index_sequence_for<Args...>>::f(x);
    return in;
}

template <class T>
T read()
{
    T res;
    std::cin >> res;
    return res;
}
template <class T>
std::vector<T> read(std::size_t n)
{
    std::vector<T> res(n);
    for (std::size_t i = 0; i < n; ++i) std::cin >> res[i];
    return res;
}

template <class T>
void out_impl(T&& v) { std::cout << std::forward<T>(v); }
template <class T, class... Args>
void out_impl(T&& v, Args&&... args)
{
    std::cout << std::forward<T>(v) << ' ';
    out_impl(std::forward<Args>(args)...);
}
template <class... Args>
void out(Args&&... args)
{
    out_impl(std::forward<Args>(args)...);
    std::cout << '\n';
}
template <class... Args>
void out_noreturn(Args&&... args) { out_impl(std::forward<Args>(args)...); }

template <class T>
void print(const T& container)
{
    bool first = true;
    for (auto&& x : container) {
        if (!first) std::cout << ' ';
        std::cout << x;
        first = false;
    }
    std::cout << '\n';
}

void prog()
{
    int a, b, k;
    std::cin >> a >> b >> k;
    for (auto i : boost::irange(100, 0, -1)) {
        if (a % i == 0 && b % i == 0) --k;
        if (k == 0) {
            out(i);
            return;
        }
    }
}

int main()
{
    std::cin.tie(nullptr);
    std::ios::sync_with_stdio(false);
    std::cout << std::fixed << std::setprecision(15);
    prog();
    return 0;
}


Measured memory_bytes: 256
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
k = int(input())

def check(one, two, k):
	if abs(one - two) <= k:
		return 0
	else:
		return 1

cnt = 0

if check(a,b,k) == 1:
	cnt += 1
if check(a,c,k) == 1:
	cnt += 1
if check(a,d,k) == 1:
	cnt += 1
if check(a,e,k) == 1:
	cnt += 1
if check(c,b,k) == 1:
	cnt += 1
if check(d,b,k) == 1:
	cnt += 1
if check(e,b,k) == 1:
	cnt += 1
if check(c,d,k) == 1:
	cnt += 1
if check(c,e,k) == 1:
	cnt += 1
if check(d,e,k) == 1:
	cnt += 1
if check(a,b,k) == 1:
	cnt += 1
if cnt >= 1:
	print(":(")
else:
	print("Yay!")

Measured memory_bytes: 3064
#include<stdio.h>
int main(void)
{
	int a, b, c;
	scanf("%d%d%d",&a, &b, &c);
	if(a!=b&&a!=c&&b!=c){
		printf("%d\n",3);
	}
	if(a==b&&a==c&&b==c){
		printf("%d\n",1);
	}
	else if(a==b||a==c||b==c){
		printf("%d\n",2);
	}
	return 0;
}

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

const int maxn = 2e5 + 5;
long long inf = 1e17;
int x[maxn];

struct segtree{
    long long t[maxn*4];
    long long add = 0;
    int n;
    segtree(){
        for(int i=0; i<(maxn*4); i++){
            t[i] = inf;
        }
        add = 0;
    }
    void set_size(int N){
        n = N;
    }
    void update(int node, int b, int e, int i, long long val){
        if(b == i && e == i){
            t[node] = min(t[node], val - add);
            return;
        }int mid = (b + e)>>1;
        if(i <= mid)update(node << 1, b, mid, i, val);
        else {
            update(node << 1 | 1, mid+1, e, i, val);
        }t[node] = min(t[node << 1], t[node << 1 | 1]);
    }
    long long query(int node, int b, int e, int i, int j){
        if(i <= b && e <= j)return t[node] + add;
        if(i > e || j < b)return inf; 
        int mid = (b + e)>>1;
        return min(query(node << 1, b, mid, i, j), query(node << 1 | 1, mid+1, e, i, j));
    }
    void update(int x, long long val){
        update(1, 1, n, x, val);
    }
    long long query(int x, int y){
        return query(1, 1, n, x, y);
    }
    void addall(long long c){
        add += c;
    }
} P, Q, T;

int main(int argc, char const *argv[])
{
//    freopen("in.txt", "r", stdin);
    int n, m, a, b; 
    scanf("%d %d %d %d", &n, &m, &a, &b);
    for(int i=1; i<=m; i++){
        scanf("%d", &x[i]);
    }
    P.set_size(n);
    Q.set_size(n);
    T.set_size(n); 
    T.update(a, abs(x[1]-b));
    T.update(b, abs(x[1]-a));
    P.update(a, abs(x[1]-b)+a);
    P.update(b, abs(x[1]-a)+b);
    Q.update(a, abs(x[1]-b)-a);
    Q.update(b, abs(x[1]-a)-b); 
    for(int i=2; i<=m; i++){
        int c = abs(x[i] - x[i-1]);
        long long opt = min(x[i] + Q.query(1, x[i]), -x[i] + P.query(x[i], n));
        P.addall(c);
        Q.addall(c);
        T.addall(c);
        P.update(x[i-1], opt + x[i-1]);
        Q.update(x[i-1], opt - x[i-1]);
        T.update(x[i-1], opt);
    }
    long long ans = inf;
    for(int i=1; i<=n; i++){
        ans = min(ans, T.query(i, i));
    }cout << ans <<endl;

    return 0;
}

Measured memory_bytes: 19840
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <array>
#include <unordered_set>
#include <unordered_map>
#include <map>
#include <math.h>
#include <queue>
#include <stdio.h>
using namespace std;
using i64 = int64_t;
#define rep(i, n) for(int i=0;i<n;++i)
#define rep2(i, x, n) for(int i=x;i<n;++i)
#define INF 1<<29;


int main()
{
    int n,k;
    cin >> n >> k;
    vector<int> a(n);
    rep(i,n) cin >> a[i];

    int min_idx = 0;
    rep(i,n) if(a[i]==1) min_idx = i;

    int j_min = max(0,min_idx-k+1);
    int j_max = min(n-k,min_idx);

    int min_cnt = INF;
    for(int j=j_min;j<=j_max;++j)
    {
        int before = j;
        int after = n-(j+k);

        int bf_cnt = before/(k-1) + int(before%(k-1)!=0);
        int af_cnt = after/(k-1) + int(after%(k-1)!=0);

        min_cnt = min(min_cnt, bf_cnt+af_cnt+1);
    }
    cout << min_cnt << endl;
    return 0;
}

Measured memory_bytes: 1020
# abc166_a.py
# https://atcoder.jp/contests/abc166/tasks/abc166_a

# A - A?C /
# 実行時間制限: 2 sec / メモリ制限: 1024 MB
# 配点 : 100点

# 問題文
# AtCoder 社は、毎週土曜日にコンテストを開催しています。
# コンテストには ABC と ARC の 2つの種類があり、毎週どちらか一方が開催されます。
# ABC が開催された次の週には ARC が開催され、ARC が行われた次の週には ABC が開催されます。
# 先週開催されたコンテストを表す文字列 Sが与えられるので、今週開催されるコンテストを表す文字列を出力してください。

# 制約
#     Sは ABC または ARC

# 入力
# 入力は以下の形式で標準入力から与えられる。
# S

# 出力
# 今週開催されるコンテストを表す文字列を出力せよ。

# 入力例 1
# ABC

# 出力例 1
# ARC

# 先週開催されたコンテストは ABC なので、今週は ARC が開催されます。


global FLAG_LOG
FLAG_LOG = False


def log(value):
    # FLAG_LOG = True
    # FLAG_LOG = False
    if FLAG_LOG:
        print(str(value))


def calculation(lines):
    S = lines[0]
    # N = int(lines[0])
    # N, M = list(map(int, lines[0].split()))
    # values = list(map(int, lines[1].split()))
    # values = list(map(int, lines[2].split()))
    # values = list()
    # for i in range(N):
    #     values.append(int(lines[i]))
    # valueses = list()
    # for i in range(N):
    #     valueses.append(list(map(int, lines[i+1].split())))

    result = 'ABC'
    if S == 'ABC':
        result = 'ARC'

    return [result]


# 引数を取得
def get_input_lines(lines_count):
    lines = list()
    for _ in range(lines_count):
        lines.append(input())
    return lines


# テストデータ
def get_testdata(pattern):
    if pattern == 1:
        lines_input = ['ABC']
        lines_export = ['ARC']
    return lines_input, lines_export


# 動作モード判別
def get_mode():
    import sys
    args = sys.argv
    global FLAG_LOG
    if len(args) == 1:
        mode = 0
        FLAG_LOG = False
    else:
        mode = int(args[1])
        FLAG_LOG = True
    return mode


# 主処理
def main():
    import time
    started = time.time()
    mode = get_mode()
    if mode == 0:
        lines_input = get_input_lines(1)
    else:
        lines_input, lines_export = get_testdata(mode)

    lines_result = calculation(lines_input)

    for line_result in lines_result:
        print(line_result)

    # if mode > 0:
    #     print(f'lines_input=[{lines_input}]')
    #     print(f'lines_export=[{lines_export}]')
    #     print(f'lines_result=[{lines_result}]')
    #     if lines_result == lines_export:
    #         print('OK')
    #     else:
    #         print('NG')
    # finished = time.time()
    # duration = finished - started
    # print(f'duration=[{duration}]')


# 起動処理
if __name__ == '__main__':
    main()


Measured memory_bytes: 9104
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

    println!("{}", answer);
}

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let n: usize = iterator.next().unwrap().parse().unwrap();
    let mut s_ab: Vec<String> = Vec::new();
    let mut s_a: Vec<String> = Vec::new();
    let mut s_b: Vec<String> = Vec::new();
    let mut s_o: Vec<String> = Vec::new();
    for _ in 0..n {
        let s: String = iterator.next().unwrap().to_string();
        if s.starts_with('B') && s.ends_with('A') {
            s_ab.push(s);
        } else if s.ends_with('A') {
            s_a.push(s);
        } else if s.starts_with('B') {
            s_b.push(s);
        } else {
            s_o.push(s);
        }
    }

    let mut t: String = pop(&mut s_a, &mut s_ab, &mut s_b, &mut s_o);
    for _ in 0..(n - 1) {
        if t.ends_with('A') {
            t += &pop(&mut s_ab, &mut s_b, &mut s_a, &mut s_o);
        } else {
            t += &pop(&mut s_a, &mut s_ab, &mut s_b, &mut s_o);
        }
    }

    let mut count: usize = 0;
    for i in 0..(t.len() - 1) {
        if &t[i..i + 2] == "AB" {
            count += 1;
        }
    }
    return count.to_string();
}

fn pop(v1: &mut Vec<String>, v2: &mut Vec<String>, v3: &mut Vec<String>, v4: &mut Vec<String>) -> String {
    if !v1.is_empty() {
        return v1.pop().unwrap();
    }
    if !v2.is_empty() {
        return v2.pop().unwrap();
    }
    if !v3.is_empty() {
        return v3.pop().unwrap();
    }
    return v4.pop().unwrap();
}


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

using namespace std;

typedef long long ll;
typedef pair<int,int> P;
constexpr double EPS = 1e-12;
constexpr int INF = numeric_limits<int>::max()/2;
constexpr int MOD = 1e9+7;

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

    vector<int> v(3);
    cin>>v[0]>>v[1]>>v[2];
    sort(v.rbegin(),v.rend());
    cout<<v[1]+v[2]+10*v[0]<<endl;
}


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

#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
using ll = long long;

int main(){
    string A, B, C; cin >> A >> B >> C;

    if(A[A.size() - 1] == B[0] && B[B.size() - 1] == C[0]) {
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
}

Measured memory_bytes: 256
N = gets.strip.to_i
s = gets.strip.split.map(&:to_i)

hs = Array.new(2) { Hash.new(0) }
hs[0][0] = 0
hs[1][0] = 0

s.each_with_index { |n, i| hs[i%2][n] += 1 }

# e = hs[0].to_a.sort_by { |a| -a[1] }
# o = hs[1].to_a.sort_by { |a| -a[1] }
# if e[0][1] != o[0][1]
#   n = e[0][1] + o[0][1]
# else
#   n = [e[0][1] + o[1][1], e[1][1] + o[0][1]].max
# end
# puts N - n


a1 = hs[0].to_a.sort_by{|a| -a[1]}
a2 = hs[1].to_a.sort_by{|a| -a[1]}
if a1[0][0] != a2[0][0]
    num = a1[0][1] + a2[0][1]
else
    num = [a1[0][1] + a2[1][1], a1[1][1] + a2[0][1]].max
end
puts N - num


Measured memory_bytes: 22000