akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;

#define int long long
typedef long long ll;
//const int INF = 2e9;
const ll INF = 9e18;

vector<int> dx = {0,1,0,-1};
vector<int> dy = {1,0,-1,0};

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    int H, W, K;
    cin >> H >> W >> K;
    int sx, sy, gx, gy;
    cin >> sx >> sy >> gx >> gy;
    sx--; sy--; gx--; gy--;
    vector<string> s(H);
    for (int i=0;i<H;i++) cin >> s[i];
    auto toId = [&] (int x, int y, int v){
        return (x*W+y)*4+v;
    };
    vector<int> dist(H*W*4,INF);
    queue<pair<int,int>> q;
    auto push = [&] (int x, int y, int v, int d){
        int id = toId(x, y, v);
        if (dist[id] <= d) return;
        dist[id] = d;
        q.emplace(d, id);
    };
    auto upK = [&] (int x){
        return ((x + K - 1)/K)*K;
    };
    for (int vv=0;vv<4;vv++) push(sx, sy, vv, 0);
    while (!q.empty()){
        int d = q.front().first;
        int id = q.front().second;
        q.pop();
        if (dist[id] != d) continue;
        int x = id/4/W;
        int y = id/4%W;
        int v = id%4;
        for (int vv=0;vv<4;vv++) push(x, y, vv, upK(d));
        int nx = x + dx[v];
        int ny = y + dy[v];
        if (nx < 0 || nx >= H) continue;
        if (ny < 0 || ny >= W) continue;
        if (s[nx][ny] == '@') continue;
        push(nx, ny, v, d+1);
    }
    int ans = INF;
    for(int vv=0;vv<4;vv++){
        ans = min(ans, dist[toId(gx,gy,vv)]);
    }
    if (ans == INF){
        cout << -1 << "\n";
    } else {
        ans = upK(ans)/K;
        cout << ans << "\n";
    }
}

Measured memory_bytes: 35668
import bisect

INF = 1 << 30

n = int(input())
a = list(map(int, input().split()))

ans = 0
now = 1

for i in range(n):
    if a[i] == now:
        now += 1
    else:
        ans += 1

if ans < n:
    print(ans)
else:
    print(-1)


Measured memory_bytes: 26140
#include <bits/stdc++.h>
using namespace std; 
#define priority_queue pq;
#define int long long
#define pu push
#define loop for(int i=0;i<n;i++)
int32_t main(){
int n;
int k;
cin>>k;
cin>>n;
int ar[n];
loop
cin>>ar[i];
int a=ar[n-1]-ar[0];
int ans=a;
for(int i=1;i<n-1;i++){
ans=min(((ar[i]-0)+(k-ar[i+1])),ans);
ans=min((k-ar[i])+ar[i-1],ans);
}ans=min((k-(ar[n-1])+ar[n-2]),ans);
cout<<ans;
}


Measured memory_bytes: 1792
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskC solver = new TaskC();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskC {
        List<Integer>[] adj;
        int[] col;
        int[] am = new int[2];
        boolean twoColorable;

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            adj = new List[n];
            for (int i = 0; i < n; i++) {
                adj[i] = new ArrayList<>();
            }
            for (int i = 0; i < m; i++) {
                int a = in.nextInt() - 1;
                int b = in.nextInt() - 1;
                adj[a].add(b);
                adj[b].add(a);
            }
            col = new int[n];
            Arrays.fill(col, -1);
            twoColorable = true;
            dfs(0, 0);
            long ans = 0;
            if (twoColorable) {
                ans = am[0] * (long) am[1];
            } else {
                ans = n * (long) (n - 1) / 2;
            }
            ans -= m;
            out.println(ans);
        }

        private void dfs(int v, int c) {
            col[v] = c;
            ++am[c];
            for (int u : adj[v]) {
                if (col[u] < 0) {
                    dfs(u, 1 - c);
                } else if (col[u] != 1 - c) {
                    twoColorable = false;
                }
            }
        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}



Measured memory_bytes: 56200
#include <bits/stdc++.h>
using namespace std;
#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(a) (a).begin(),(a).end()		//sort(all(vi S)) sort(all(string S))

typedef long long ll;
typedef vector<int> vi;
typedef set<int> seti;
typedef vector<string> vs;

const int MOD = 1e9+7;
const int INF = 1e9;

int main() {
	string S;
	cin>>S;
	string ans = "NO";
	int N = S.size();
	for (int i = 0; i < N; ++i){
		for (int j = i; j < N; ++j){
			string Sc;
			Sc+=S.substr(0,i)+S.substr(j,N-j);
			if(Sc=="keyence")ans="YES";
		}
	}
	cout<<ans<<endl;
}

Measured memory_bytes: 256
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

class Dijkstra():
    def __init__(self):
        self.e = collections.defaultdict(list)

    def add(self, u, v, d):
        self.e[u].append([v,d])
        self.e[v].append([u,d])

    def delete(self, u, v):
        self.e[u] = [_ for _ in self.e[u] if _[0] != v]
        self.e[v] = [_ for _ in self.e[v] if _[0] != u]

    def search(self, s):
        d = collections.defaultdict(lambda: inf)
        d[s] = 0
        q = []
        heapq.heappush(q, (0, s))
        v = collections.defaultdict(bool)
        while len(q):
            k, u = heapq.heappop(q)
            if v[u]:
                continue
            v[u] = True

            for uv, ud in self.e[u]:
                if v[uv]:
                    continue
                vd = k + ud
                if d[uv] > vd:
                    d[uv] = vd
                    heapq.heappush(q, (vd, uv))

        return d

def main():
    n,m,s,t = LI()
    aa = [LI() for i in range(m)]
    d1 = Dijkstra()
    d2 = Dijkstra()
    for u,v,a,b in aa:
        d1.add(u,v,a)
        d2.add(u,v,b)
    ad = d1.search(s)
    bd = d2.search(t)
    rr = [inf]
    for i in range(n,0,-1):
        tr = ad[i] + bd[i]
        if tr > rr[-1]:
            tr = rr[-1]
        rr.append(tr)

    return '\n'.join(map(lambda x: str(10**15-x), rr[1:][::-1]))


print(main())



Measured memory_bytes: 149348
#include<cstdio>
#include<cstring>
#include<algorithm>
typedef long long ll;
using namespace std;
const int maxn=1e6+5;
const int MAXN=1e7+5;


int main()
{
    int x;
    ll ans=0;
    scanf("%d",&x);
    ans+=1ll*(x/500)*1000;
    x-=x/500*500;
    ans+=1ll*x/5*5;
    printf("%lld\n",ans);
}

Measured memory_bytes: 888
#include <iostream>
using namespace std;
 
int main() {
    int n, m;
    cin >> n >> m;
    int A[n][m];
    int B[m];
    for (int i=0;i<n;i++) {
        for (int j=0;j<m;j++) {
            cin >> A[i][j];
        }
    }
    for (int j=0;j<m;j++) {
        cin >> B[j];
    }

    int C[n];
    for (int i=0;i<n;i++) {
        C[i] = 0;
    }
    for (int i=0;i<n;i++) {
        for (int j=0;j<m;j++) {
            C[i] += A[i][j] * B[j];
        }
    }
    for (int i=0;i<n;i++) {
        cout << C[i] << endl;
    }
    return 0;
}



Measured memory_bytes: 3120
#include <bits/stdc++.h>
#include <limits>
#include <math.h>
#include <cmath>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int> ;
using vi = vector<int> ;
using vvi = vector<vector<int>> ;
using vll = vector<long long>;
using vvll = vector<vector<long long >>;
#define PI 3.141592653
#define rep(i, n) for(ll i = 0; i < n; i++)



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

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

  sort(v.begin(), v.end());

  ll sum = 0;
  rep(i,k){sum += v[i];}

  cout << sum << endl;

}

Measured memory_bytes: 3632
#ifdef __APPLE__
#include <iostream>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <set>
#include <algorithm>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <random>
#else
#include <bits/stdc++.h>
#endif

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 vector<long long int> VLLI;
typedef vector<pair<int, int> > VPI;
typedef long long ll;
typedef pair<int,int> PII;
mt19937 mrand(random_device{}()); 
const ll mod=1000000007;
int rnd(int x) { return mrand() % x;}
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;}
// head

int main() {
    int x, y;
    cin >> x >> y;
    int ans = 0;
    if (x == y and x == 1) {
        ans += 400000;
    }

    if (x == 1) {
        ans += 300000;
    } else if (x == 2) {
        ans += 200000;
    } else if (x == 3) {
        ans += 100000;
    }
    
    if (y == 1) {
        ans += 300000;
    } else if (y == 2) {
        ans += 200000;
    } else if (y == 3) {
        ans += 100000;
    }

    cout << ans << "\n";
}



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

typedef long long ll;
typedef long double ld;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<string> vstr;

typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ub upper_bound
#define lb lower_bound
#define asd cout << "ok" << endl;

#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define trav(it, m) for(auto it = m.begin(); it it!= m.end(); it++)

const char nl = '\n';
const int MOD = 1e9 +7;
const ll INF = 1e19;
const ld PI = acos((ld)-1);
const int MX = 2e5 + 5;

int main(){

  ios_base::sync_with_stdio(0); cin.tie(0);
  int n; cin >>n ;
  int maxN = -1;
  int sum = 0;
  for(int i = 0; i < n; i++){
    int x; cin >> x;
    sum += x;
    maxN = max(maxN, x);
  }
  if(maxN < sum - maxN){
    cout << "Yes" << nl;
    return 0;
  }
  cout << "No" << nl;





  return 0;
}



Measured memory_bytes: 3612
#include <bits/stdc++.h>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <numeric>
using namespace std;

int abs(int num){
   if (num > 0)
      return num;
   else
      return -num;
}

int main(){
  int N;
  cin >> N;
  int A;
  cin >> A;
  cout << N*N-A << endl;
}

Measured memory_bytes: 256
Row = int(input())
List = []
for i in range (Row):
  List.append(list(map(int, input().split())))
List = sorted(List, key=lambda x: x[1])  #[1]に注目してソート
res = 0
flag = True
for i in range(Row):
  res += List[i][0]
  if res > List[i][1]:
    flag = False
    break
if flag:
  print("Yes")
else:
  print("No")

Measured memory_bytes: 48424
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>

using namespace std;

#define FOR(i,k,n) for(int i=(k); i<(int)n; ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)

template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; }

typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;

int main(){
  int N, M, W, T;
  while(cin>>N>>M>>W>>T){
    map<string, int> product_id;
    string name[7];
    int weight[7] = {};
    int value[7] = {};
    REP(i, M){
      cin>>name[i]>>weight[i]>>value[i];
      product_id[name[i]] = i;
    }
    int L[8] = {}, X[8] = {}, Y[8] = {};
    string t_name[8][8];
    int t_value[8][8];
    REP(i, N){
      cin>>L[i]>>X[i]>>Y[i];
      REP(j, L[i]){
        cin>>t_name[i][j]>>t_value[i][j];
      }
    }

    int tsp[1<<8][8] = {};
    REP(i, 1<<8)REP(j, 8) tsp[i][j] = INF;
    REP(i, N) tsp[1<<i][i] = abs(X[i]) + abs(Y[i]);
    for(int S = 1; S < (1<<(N + 1)); S++){
      for(int from = 0; from < N; from++)if(S & (1<<from)){
        for(int to = 0; to <= N; to++)if(!(S & (1<<to))){
          tsp[S | (1<<to)][to] = min(tsp[S | (1<<to)][to], tsp[S][from] + abs(X[from] - X[to]) + abs(Y[from] - Y[to]));
        }
      }
    }

    int dist[1<<7] = {};
    for(int S = 1; S < 1<<N; S++) dist[S] = tsp[S | (1<<N)][N];

    int obtain[1<<7] = {};
    for(int S = 1; S < 1<<N; S++){
      int v[7];
      fill(v, v+7, INF);
      REP(i, N) if(S & (1<<i)){
        REP(j, L[i]) v[product_id[t_name[i][j]]] = min(v[product_id[t_name[i][j]]], t_value[i][j]);
      }
      int dp[10001] = {};
      for(int i = 0; i <= W; i++){
        for(int j = 0; j < M; j++){
          if(weight[j] + i <= W)dp[weight[j] + i] = max(dp[weight[j] + i], dp[i] + value[j] - v[j]);
        }
        obtain[S] = max(obtain[S], dp[i]);
      }
    }
    ll dp[10002] = {};
    ll ans = 0;
    for(int t = 0; t <= T; t++){
      for(int S = 1; S < 1<<N; S++){
        if(t + dist[S] <= T) dp[t + dist[S]] = max(dp[t + dist[S]], dp[t] + obtain[S]);
      }
      //printf("t:%d dp:%d\n", t, dp[t]);
      ans = max(ans, dp[t]);
    }
    cout<<ans<<endl;
  }
  return 0;
}

Measured memory_bytes: 1352
N=int(input())
S=list(map(int,input().split()))
Z=[]
tmp=[]
for i in range(N):
    Z.append(S[i])
    tmp.append(S[i])
    

Z.sort()


for i in range(N):
    for j in range(N):
        
        R=tmp[i]
        tmp[i]=tmp[j]
        tmp[j]=R
        if tmp==Z:
            print("YES")
            exit()
        R=tmp[i]
        tmp[i]=tmp[j]
        tmp[j]=R        
        

print("NO")


Measured memory_bytes: 3064
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <utility>
#include <string>
using namespace std;

int main() {
	int a,b,c;
	cin>>a>>b>>c;
	cout<<((a+b)*c)/2;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <unordered_map>
#define ull unsigned long long
#define int long long
#define ll long long
#define fr(i, n) for (int i = 0; i < n; i++)
#define frf(i, j, n) for (int i = j; i <= n; i++)
#define frd(i, n) for (int i = n; i >= 0; i--)
#define mp(i, j) make_pair(i, j)
#define pb(x) push_back(x)
using namespace std;
// typedef vector<vector<ll>> matrix;
// const ll PRIME = 1e9 + 7;
// typedef pair<int,pair<int,int> >  ppi;
void solve()
{
    int a,b,c,k;
    cin>>a>>b>>c>>k;
    if(b>a && c>b)
    {
        cout<<"Yes\n";
        return;
    }
    int ans=0;
    if(a>=b)
    {
       while (a>=b)
       {
           ans++;
           b*=2;
       }
       
    }
    while (b>=c)
    {
        ans++;
        c*=2;
    }
    if(ans<=k)
    cout<<"Yes\n";
    else
    {
        cout<<"No\n";
    }
    
    
    
}
int32_t main()
{

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

    int t;
    // cin >> t;
    t = 1;
    while (t--)
    {

        solve();
    }
}

Measured memory_bytes: 3644
#E
from itertools import accumulate
from bisect import bisect_left
def main():
    n,m=map(int,input().split())
    A=list(map(int,input().split()))
    A.sort()
    
    def count(k):
        cnt=0
        for a in A:
            cnt+=bisect_left(A,k-a)
        return cnt
    
    ok=0
    ng=10**10+1
    while ng-ok>1:
        mid=(ok+ng)//2
        if count(mid)<n**2-m:
            ok=mid
        else:
            ng=mid
    border=ok
    
    k=n**2-count(border)
    Acc=[0]+list(accumulate(A))
    s=Acc[-1]
    ans=0
    for a in A:
        idx=bisect_left(A,border-a)
        ans+=a*(n-idx)+(s-Acc[idx])
    ans-=border*(k-m)
    print(ans)
    
if __name__=='__main__':
    main()

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

int main(){
  int A;
  int T;
  cin >> A >> T;
  vector<int> tastes(A);
  for (int i = 0; i < A; i++){
    tastes.at(i) = i + T;
  }
  int ans = 0;
  for (int x : tastes) ans += x;
  if (A > 0 - T && T <= 0) cout << ans << endl;
  else if (T < 0) cout << ans - tastes.at(A - 1) << endl;
  else cout << ans - tastes.at(0) << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <bits/stdc++.h> 
using namespace std;
typedef long long ll;  
            
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	char ch;
	cin>>ch;
	int x=(int)ch;
	if(x>90)
	cout<<'a'<<endl;
	else
	cout<<'A'<<endl;
	return 0;
}

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

int main() {
    ll n, d;
    cin >> n >> d;

    ll cnt = 0;
    for (int i = 0; i < n; i++) {
        ll x, y;
        cin >> x >> y;

        if (x*x + y*y <= d*d) cnt++;
    }

    cout << cnt << endl;
}

Measured memory_bytes: 3608
#include<bits/stdc++.h>
//#include <numeric>
using namespace std;
#define int long long
int32_t main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    #ifdef LOCAL_PROJECT
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    #endif
    int n,i;
    cin>>n;
    int dp[n];
    int a[n];
    for(i=0;i<n;i++)
        cin>>a[i];
    dp[0]=0;
    dp[1]=abs(a[1]-a[0]);
    for(i=2;i<n;i++)
    {
       dp[i]=min(dp[i-1]+abs(a[i]-a[i-1]),dp[i-2]+abs(a[i]-a[i-2]));
    }
   cout<<dp[n-1];
}

Measured memory_bytes: 1792
n,m = map(int,input().split())
p = list(map(int,input().split()))
p = list(enumerate(p,start=1))
#print(p)
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
        self.size = [1] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
            self.size[x] = 0
        else:
            self.par[y] = x
            self.size[x] += self.size[y]
            self.size[y] = 0
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

uf = UnionFind(n)
for m in range(m):
    x,y = map(int,input().split())
    uf.union(x,y)

ans = 0
for now,value in p:
    if uf.same_check(now,value):
        ans += 1
print(ans)


Measured memory_bytes: 100716
fun main(args: Array<String>) {
    val (N,M) = readLine()!!.split(" ").map { it.toInt() }
    val a = (1..N).map { readLine()!!.split(" ").map { it.toLong() } }
    val b = (0..7).map {
        val xp: Int = it % 2
        val yp: Int = (it/2)%2
        val zp: Int = (it/4)%2

        a.map {
            val x = if(xp==0) it[0] else -it[0]
            val y = if(yp==0) it[1] else -it[1]
            val z = if(zp==0) it[2] else -it[2]
            x + y + z
        }
                .sortedDescending()
                .subList(0, M)
                .sum()
    }.max()
    println(b)
}

Measured memory_bytes: 41160
#include <bits/stdc++.h>
using namespace std;int64_t N,P,p,i,r,v,m[1<<20];string S;main(){cin>>N>>P>>S;if(10%P)for(m[0]=p=1,i=N;i--;)r+=m[v=(v+(S[i]-48)*(p=(p*10)%P))%P]++;else{for(;i<N;i++)if(!((S[i]-8)%P))r+=i+1;}cout<<r;}

Measured memory_bytes: 644
#include <bits/stdc++.h>
using namespace std;
constexpr int P = 998244353;
int power(int base, int exp) {
    int result = 1;
    while (exp > 0) {
        if (exp & 1)
            result = 1LL * result * base % P;
        base = 1LL * base * base % P;
        exp >>= 1;
    }
    return result;
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    cin >> n >> m;
    int l = max(n, m);
    vector<int> factorial(l + 1), inv_factorial(l + 1);
    factorial[0] = 1;
    for (int i = 1; i <= l; ++i)
        factorial[i] = 1LL * factorial[i - 1] * i % P;
    inv_factorial[l] = power(factorial[l], P - 2);
    for (int i = l; i >= 1; --i)
        inv_factorial[i - 1] = 1LL * inv_factorial[i] * i % P;
    auto binom = [&](int n, int m) {return 1LL * factorial[n] * inv_factorial[m] % P * inv_factorial[n - m] % P;};
    int ans = 0;
    for (int i = min(n, m), x = 1LL * power(m + 1, n - i) * power(n + 1, m - i) % P; i >= 0; --i) {
        int res = 1LL * binom(n, i) * binom(m, i) % P * factorial[i] % P * x % P;
        x = 1LL * x * (n + 1) % P * (m + 1) % P;
        if (i % 2 == 0)
            ans = (ans + res) % P;
        else
            ans = (ans - res + P) % P;
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 4224
import java.util.Scanner;

public class Main {

    public static void main(String[] args)  {
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
        int f = a % b;
        int t = a;
        while (true){
            if(t % b == c){
                System.out.println("YES");
                return;
            }
            t += a;
            if(f == t % b)break;
        }
        System.out.println("NO");
    }

}



Measured memory_bytes: 23252
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int n,m,a,b,ans;
string t,s[50];
int main(void){
    while(1){
    cin>>n>>m;
    if(n==0&&m==0)return 0;
    map<char,int> mpx,mpy;
    for(int i=0;i<n;i++){
        cin>>s[i];
        for(int j=0;j<m;j++){
            if(s[i][j]=='_')continue;
            mpx[s[i][j]]=i;
            mpy[s[i][j]]=j;
        }
    }
    a=0;b=0;
    ans=0;
    cin>>t;
    for(int i=0;i<t.size();i++){
        ans+=abs(mpx[t[i]]-a)+abs(mpy[t[i]]-b);
        a=mpx[t[i]],b=mpy[t[i]];
    }
    cout<<ans+t.size()<<endl;
    }
}



Measured memory_bytes: 3172
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
const ll mod = 1000000007;
const int INF = 1001001001;

int main(){
    int h,w,n; cin >> h >> w >> n;
    cout << min(((n+h-1)/h),((n+w-1)/w)) << endl;
}


Measured memory_bytes: 256
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <numeric>
#include <bitset>

using namespace std;

using ll =  long long;
using Pll = pair<ll, ll>;
using Pii = pair<int, int>;

constexpr ll MOD = 1000000007;
constexpr long double EPS = 1e-10;
constexpr int dyx[4][2] = {
    { 0, 1}, {-1, 0}, {0,-1}, {1, 0}
};

void print_edge(int x, int y) {
    cout << x << " " << y << endl;
}

int main() {
    std::ios::sync_with_stdio(0); cin.tie(0);
    int n;
    cin >> n;
    {
        int m = 1;
        while(m < n) m <<= 1;
        if(n <= 2 || n == m) {
            cout << "No" << endl;
            return 0;
        }
    }
    
    cout << "Yes" << endl;

    print_edge(1, 2);
    print_edge(2, 3);
    print_edge(3, n+1);
    print_edge(n+1, n+2);
    print_edge(n+2, n+3);

    for(int i=4;i+1<=n;i+=2) {
        print_edge(i, i+1);
        print_edge(i+1, n+1);
        print_edge(n+1, n+i);
        print_edge(n+i, n+i+1);
    }

    if(n % 2 == 0) {
        for(int i=3;i<n;i+=2) {
            if(n & (i ^ 1)) {
                int a = i ^ 1;
                int b = n ^ a;
                print_edge(n, i);
                print_edge(n+b, 2*n);
                break;
            }
        }
    }

}


Measured memory_bytes: 2816
N, M = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(M)]
ab.sort(key=lambda x: x[1])
ans = 1
tmp = ab[0][1]
for i in range(1, M):
    if tmp <= ab[i][0]:
        ans += 1
        tmp = ab[i][1]
print(ans)

Measured memory_bytes: 29084
#include<stdio.h>
int A[1000000],n;

int binarySearch(int key){
    int left = 0;
    int right = n;
    int mid;
while (left < right){
    mid=(left+right)/2;
    if(key==A[mid])return 1;
    if(key>A[mid])left=mid+1;
    else if(key<A[mid])right=mid;
}
return 0;
}


int main(void){
    int i,q,k,sum=0;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%d",&A[i]);
    }
    scanf("%d",&q);
    for(i=0;i<q;i++){
        scanf("%d",&k);
        if(binarySearch(k))
            sum++;
    }
    printf("%d\n",sum);
    return 0;
}


Measured memory_bytes: 2136
#pragma GCC optimize("O3")
#include <bits/stdc++.h>
#define ll long long
#define rep2(i,a,b) for(ll i=a;i<=b;++i)
#define rep(i,n) for(ll i=0;i<n;i++)
#define rep3(i,a,b) for(ll i=a;i>=b;i--)
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pq priority_queue
#define pb push_back
#define eb emplace_back
#define vec vector<int>
#define vecll vector<ll>
#define vecpii vector<pii>
#define vec2(a,b) vector<vec>(a,vec(b))
#define vec2ll(a,b) vector<vec>(a,vecll(b))
#define vec3(a,b,c) vector<vector<vec>>(a,vec2(b,c))
#define vec3ll(a,b,c) vector<vector<vecll>>(a,vec2ll(b,c))
#define fi first
#define se second
#define endl "\n"
#define all(c) begin(c),end(c)
#define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
#define lb(c,x) distance(c.begin(),lower_bound(all(c),x))
#define ub(c,x) distance(c.begin(),upper_bound(all(c),x))
#define MM " "
using namespace std;
int in() {int x;cin>>x;return x;}
ll lin() {ll x;cin>>x;return x;}
template<class T> inline bool chmax(T& a,T b){if(a<b){a=b;return 1;}return 0;}
template<class T> inline bool chmin(T& a,T b){if(a>b){a=b;return 1;}return 0;}
template<class T> inline void print(pair<T,T> p){cout<<"("<<p.first<<","<<p.second<<") ";}
template<class T> inline void print(vector<pair<T,T>> v){for(auto e:v)print(e); cout<<endl;}
template<class T> inline void print(T v){for(auto e:v)cout<<e<<" ";cout<<endl;}



ll dp[21000];
main(){
    int n=in(),d=in(),a=in();
    vector<pll> b;
    rep(i,n){
        ll x=in(),h=in();
        b.eb(x,h);
    }
    sort(all(b));
    vector<ll> r(n+3);
    ll ans=0;
    rep(i,n){
        b[i].second-=r[i];
        if(b[i].second>0){
            ll t=(b[i].second+a-1)/a;
            ans+=t;
            r[i]+=t*a;
            int s=distance(b.begin(),upper_bound(all(b),pll{b[i].first+2*d,1e9}));
            r[s]-=t*a;
        }
        r[i+1]+=r[i];
        // cout<<ans<<endl;
    }
    cout<<ans<<endl;
}


Measured memory_bytes: 6256
#include<bits/stdc++.h>
#define fi first
#define se second
#define lc (x<<1)
#define rc (x<<1|1)
#define gc getchar()//(p1==p2&&(p2=(p1=buf)+fread(buf,1,size,stdin),p1==p2)?EOF:*p1++)
#define mk make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define pb push_back
#define IT iterator 
#define vi vector<int>
#define TP template<class o>
#define SZ(a) ((int)a.size())
#define all(a) a.begin(),a.end()
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const int N=2e5+10,size=1<<20,mod=998244353,inf=2e9;

//char buf[size],*p1=buf,*p2=buf;
template<class o> void qr(o &x) {
    char c=gc; x=0; int f=1;
    while(!isdigit(c)){if(c=='-')f=-1; c=gc;}
    while(isdigit(c)) x=x*10+c-'0',c=gc;
    x*=f;
}
template<class o> void qw(o x) {
    if(x/10) qw(x/10);
    putchar(x%10+'0');
}
template<class o> void pr1(o x) {
    if(x<0)x=-x,putchar('-');
    qw(x); putchar(' ');
}
template<class o> void pr2(o x) {
    if(x<0)x=-x,putchar('-');
    qw(x); putchar('\n');
}

int n,cnt[N],L[N],R[N];
char s[N];
int main() {
    scanf("%s",s+1);n=strlen(s+1);
    for(int i=1;i<=n;i++) 
        if(s[i]=='L') L[i]=(s[i-1]=='L')?L[i-1]:i;
    for(int i=n;i;i--)
        if(s[i]=='R') R[i]=(s[i+1]=='R')?R[i+1]:i;
    for(int i=1;i<=n;i++) {
        if(s[i]=='L') {
            int t=((i-L[i]+1)&1)^1;
            cnt[L[i]-t]++;
        }
        else  {
            int t=((R[i]-i+1)&1)^1;
            cnt[R[i]+t]++;
        }
    }
    for(int i=1;i<=n;i++) pr1(cnt[i]);
    return 0;
}

Measured memory_bytes: 4916
#

import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop

def main():
    n = int(input())
    hl = list(map(int, input().split()))

    if n == 1:
        print('Yes')
        return

    prev = None
    hl.reverse()
    for i in range(1, len(hl)):
        if hl[i-1] < hl[i]: # 減少したらダメ
            if hl[i-1] == hl[i] - 1:
                hl[i] = hl[i] - 1
            else:
                print('No')
                return
        else:
            continue

    print('Yes')
    return

if __name__ == '__main__':
    main()


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

typedef long long LL;
const int N = 2e5 + 5;
const LL mod = 1e9 + 7;

LL fac[N], inv[N];

inline LL pow(LL x, LL exp) {
  LL ret = 1;
  while (exp) {
    if (exp & 1) ret = ret * x % mod;
    exp >>= 1;
    x = x * x % mod;
  }
  return ret;
}

inline void pre() {
  fac[0] = inv[0] = 1;
  for (LL i = 1; i < N; i ++) fac[i] = fac[i - 1] * i % mod;
  inv[N - 1] = pow(fac[N - 1], mod - 2);
  for (LL i = N - 2; i >= 1; i --) inv[i] = inv[i + 1] * (i + 1) % mod;
}

inline LL Co(int n, int m) {
  return fac[n] * inv[m] % mod * inv[n - m] % mod;
}

int main() {
  pre();
  int n, m, a, b;
  LL ans = 0;
  scanf("%d%d%d%d", &n, &m, &a, &b);
  for (int i = b + 1; i <= m; i ++) {
    int r1 = i - 1, d1 = n - a - 1;
    int r2 = m - 1 - r1, d2 = n - 2 - d1;
    ans += Co(r1 + d1, r1) * Co(r2 + d2, r2) % mod;
    if (ans >= mod) ans -= mod;
  }
  printf("%lld\n", ans);
  return 0;
}


Measured memory_bytes: 3328
N = int(input())
A = list(map(int,input().split()))

direc = ""
ans = 0
for i in range(N-1):
  d = A[i+1] - A[i]
  if direc == "":
    if d > 0:
      direc = "up"
    elif d < 0:
      direc = "down"
  else:
    if direc == "up" and d < 0:
      ans += 1
      direc = ""
    elif direc == "down" and d > 0:
      ans += 1
      direc = ""
print(ans+1)

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

#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)

using namespace std;

typedef long long ll;

const int MAX = 100100;
int N,M,P[MAX];
ll A[MAX],B[MAX],C[MAX],imos[MAX];

int main(){
  cin >> N >> M;
  rep(i,M) { cin >> P[i]; --P[i]; }
  rep(i,N-1) cin >> A[i] >> B[i] >> C[i];
  rep(i,M-1) ++imos[(int)min(P[i],P[i+1])], --imos[(int)max(P[i],P[i+1])];
  REP(i,1,N-1) imos[i] += imos[i-1];
  ll mini = 0;
  rep(i,N-1) mini += min(imos[i]*A[i],imos[i]*B[i]+C[i]);
  cout << mini << endl;
  return 0;
}

Measured memory_bytes: 4684
from functools import reduce
import math

def main():
    # 文字列の2進数を数値にする
    # '101' → '5'
    # 文字列の頭に'0b'をつけてint()にわたす
    # binary = int('0b'+'101',0)

    # 2進数で立っているbitを数える
    # 101(0x5) → 2
    # cnt_bit = bin(5).count('1')
    
    # N! を求める
    # f = math.factorial(N)
    
    # 切り捨て
    # 4 // 3
    # 切り上げ
    #-(-4 // 3)
    
    # 初期値用:十分大きい数(100億)
    INF = float("inf")
    
    # 1文字のみを読み込み
    # 入力:2
    # a = input().rstrip()
    # 変数:a='2'
    
    # スペース区切りで標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a, b, c, d = (int(_) for _ in input().split())  
    # 変数:a=2 b=4 c=5 d =7
    
    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2 4 5 7
    # a = list(int(_) for _ in input().split())
    # 変数:a = [2, 4, 5, 7]    

    # 1文字ずつ標準入力を配列として読み込み
    # 入力:2457
    # a = list(int(_) for _ in input())
    # 変数:a = [2, 4, 5, 7]    
    a, b, c = (int(_) for _ in input().split())
    if (c > a and c < b) or (c > b and c < a):
        print('Yes')
    else:
        print('No')
    
if __name__ == '__main__':
    main()


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

using namespace std;

#define REP(i,n) for(int i=0;i<(n);i++)
#define ALL(a)  (a).begin(),(a).end()
using ll = long long;
using Pair = pair<int, int>;
const ll mod = 1e9 + 7;

int main(int argc, char const* argv[])
{
  int m, n;

  cin >> m >> n;
  if (m == n) cout << "Yes" << endl;
  else cout << "No" << endl;

  return 0;
}

Measured memory_bytes: 256
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long; 
using pii =  pair<int, int>;
using pll =  pair<long long, long long>;
#define rep(i, n) for(int i = 0; i < (n); ++i)
#define all(x) (x).begin(),(x).end()
constexpr char ln =  '\n';
constexpr long long MOD = 1000000007LL;
//constexpr long long MOD = 998244353LL;
template<class T, class U> inline bool chmax(T &a, U b) { if (a < b) { a = b; return true;} return false; }
template<class T, class U> inline bool chmin(T &a, U b) { if (a > b) { a = b; return true;} return false; }
const ll INF = (ll)1e18 + 1;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int a,b; cin >> a >> b;
    
    cout << (a-1)*(b-1) << ln;
    return 0;
}

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

#define int long long
#define ll long long
#define f1(i,a,b) for(i=a;i<b;i++)
#define f2(i,a,b) for(i=a;i>=b;i--)
#define endl '\n'
#define pb push_back
#define gp " "
#define ff first
#define ss second
#define mp make_pair

const int mod=1000000007;
int i,j;
ll temp;

int32_t main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    // #ifndef ONLINE_JUDGE
    // 	freopen("/home/akmittal/Desktop/Competitive Programming/in.txt","r",stdin);
    // 	freopen("/home/akmittal/Desktop/Competitive Programming/out.txt","w",stdout);
    // #endif
    int n;
    cin>>n;
    vector<string> a;
    f1(i,0,n)
    {
    	string s;
    	cin>>s;
    	sort(s.begin(),s.end());
    	a.pb(s);
    }
    sort(a.begin(),a.end());
    a.pb("a");
    int start=0;
    int ans=0;
    f1(i,1,n+1)
    {
    	//cout<<a[i]<<endl;
    	if(a[i]!=a[i-1])
    	{
    		ans+=((i-start-1)*(i-start))/2;
    		start=i;
    	}
    }
 //    if(start!=n&&start)
 //    {
 //    	i=(n-1);
 //    	ans+=(i-start+1)*(i-start)/2;
	// }
	cout<<ans;
    return 0;
}

Measured memory_bytes: 5748
#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main(){
  char mihon[11], input[1001], eot[]="END_OF_TEXT";
  int i, count=0;

  scanf("%s",mihon);
  
  while(1){
    scanf("%s",input);
    if(strcmp(input,eot)==0) break;

    for(i=0;input[i]!='\0';i++) input[i]=tolower(input[i]);

    if(strcmp(input,mihon)==0) count++;
  }

  printf("%d\n",count);
  
  return 0;
}



Measured memory_bytes: 2140
import java.util.*;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long x = sc.nextLong();
        long a = 100L;
        int b = 0;
        for (int i = 1; i < 1000000; i++) {
            a = (long)(a * 1.01);
            if(x <= a){
                b = i;
                break;
            }
        }
        System.out.println(b);
        sc.close();

    }

}


Measured memory_bytes: 35760
#include <bits/stdc++.h>
#define syosu(x) fixed<<setprecision(x)
using namespace std;
typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef pair<double,double> pdd;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<string> vs;
typedef vector<P> vp;
typedef vector<vp> vvp;
typedef vector<pll> vpll;
typedef pair<int,P> pip;
typedef vector<pip> vip;
const int inf=1<<30;
const ll INF=1ll<<60;
const double pi=acos(-1);
const double eps=1e-9;
const ll mod=1e9+7;
const int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};

int n;
vl a;

int main(){
	cin>>n;
	a=vl(n);
	for(auto &i:a) cin>>i;
	sort(a.begin(),a.end());
	ll res=0,t=1,s=1,x=1;
	for(int i=0;i<n;i++) (x*=4)%=mod;
	for(int i=n-1;i>=0;i--){
		(x*=mod/2+1)%=mod;
		(res+=a[i]*t%mod*x)%=mod;
//		cout<<2*t-1<<' '<<x<<' '<<a[i]<<endl;
		t=(2*t+s)%mod;
		(s*=2)%=mod;
	}
	cout<<res<<endl;
}

Measured memory_bytes: 1792
#include <stdio.h>
#define N 100005
 
int A[N];

int Partition(int *,int,int);

int main(){
    int n,i,x;
     
    scanf("%d",&n);
     
    for(i=0;i<n;i++){
        scanf("%d",&A[i]);
    }
     
     
    x=Partition(A,0,n-1);
     
    for(i=0;i<x;i++){
        printf("%d ",A[i]);
    }
    printf("[%d] ",A[x]);
     
    for(i=x+1;i<n-1;i++){
        printf("%d ",A[i]);
    }
    printf("%d\n",A[n-1]);
     
    return 0;
}

int Partition(int A[],int p,int r){
    int x,i,j,tmp;
     
    x=A[r];
    i = p-1;
     
    for(j=p;j<r;j++){
        if (A[j] <= x){
            i=i+1;
            tmp=A[j];
            A[j]=A[i];
            A[i]=tmp;
        }
    }
 
        tmp=A[i+1];
        A[i+1]=A[r];
        A[r]=tmp;
     
    return i+1;
}

Measured memory_bytes: 988
from heapq import heappush, heappop
inf = float('inf')
mod = 10**9 + 7

# ダイクストラ法 計算量O(ElogV)
# [引数]: 隣接リスト, 始点
class dijkstra:
    def __init__(self, to:list, start:int):
        self.N = len(to)
        self.to = [s[:] for s in to]
        self.start = start
        self.dist = [inf] * self.N
        self.dist[start] = 0
        # cnt : 最短経路の数
        self.cnt = [0] * self.N
        self.cnt[start] = 1
        self.pq = [(self.dist[start], start)]

    # distを更新
    def update(self) -> None:
        while self.pq:
            _, v = heappop(self.pq)
            for nv, w in self.to[v]:
                if self.dist[nv] > self.dist[v] + w:
                    self.dist[nv] = self.dist[v] + w
                    heappush(self.pq, (self.dist[nv], nv))
                if self.dist[nv] == self.dist[v] + w:
                    self.cnt[nv] += self.cnt[v]
                    self.cnt[nv] %= mod

N, M, r = map(int,input().split())
to = [[] for _ in range(N)]
for _ in range(M):
    s, t, d = map(int,input().split())
    to[s].append((t, d))

DI = dijkstra(to, r)
DI.update()
for d in DI.dist:
    if d == inf:
        print("INF")
    else:
        print(d)


Measured memory_bytes: 100800
using System;
using System.Collections.Generic;

public class Program222 // ←Class名変更！！
{
    public static void Main(string[] args)
    {
        var xy = Console.ReadLine().Split(' ');
        var n = int.Parse(xy[0]);  //x,y なのか y,xなのか注意
        var t = int.Parse(xy[1]);

        var result = "TLE";
        var minC = 1001;

        for (int i = 0; i < n; i++)
        {
            var xy22 = Console.ReadLine().Split(' ');
            var c = int.Parse(xy22[0]);  //x,y なのか y,xなのか注意
            var tn = int.Parse(xy22[1]);

            if (c < minC && tn <= t)
            {
                minC = c;
            }

        }

        if (minC==1001)
        {
            Console.WriteLine("TLE");
        }
        else
        {
            Console.WriteLine(minC.ToString());

        }

    } // Main
}     // Class




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

using namespace std;

int a[20];

int main() {
	int x, y, z;
	scanf("%d %d %d", &x, &y, &z);
	a[x]++;
	a[y]++;
	a[z]++;
	if (a[5] == 2 && a[7] == 1) {
		puts("YES");
	} else {
		puts("NO");
	}
	return 0;
}

Measured memory_bytes: 256
import java.util.Scanner;

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

		String s1=sc.next();
		String s2[]=s1.split("");
		int count=0;
		for(String s:s2) {
			if(s.equals("1")) count++;
		}
		System.out.print(count);
	}
}

Measured memory_bytes: 35516
import Data.List
import Data.Ord

main = interact $ unlines . map (unwords . map show . flying_jenny . map read . words) . lines

flying_jenny :: [Int] -> [Int]
flying_jenny ns = fst $ head $ sortBy (comparing snd) $ sortBy (comparing fst) $
 [(p,w) | p <- take 8 $ map (take 8) $ tails $ cycle [4,1,4,1,2,1,2,1], let w = sum $ zipWith (\x y -> max 0 (x-y)) ns p]

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

N, M = map(int, input().split())
# N-1辺表示をグラフ表示に
graph = [[] for _ in range(N)]
for _ in range(M):
    a, b = map(int, input().split())
    graph[a-1].append(b-1)
S, T = map(lambda x:int(x)-1, input().split())


q = {S}
checked = [False]*N
checked[S] = True

ok = False
c = 0
while q:
    c += 1
    qq = set()
    if c % 3 == 0:
        for p in q:
            for np in graph[p]:
                if np == T:
                    ok = True
                    break
                if not checked[np]:
                    qq.add(np)
                    checked[np] = True
    else:
        for p in q:
            for np in graph[p]:
                qq.add(np)
    if ok:
        break
    q = qq

if ok:
    print(c//3)
else:
    print(-1)

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

#define REP(i,num) for(int i=0;i<(num);++i)
#define ALL(c) c.begin(),c.end()
#define LOOP(i) while(i--)
#define PRINTALL(c) for(auto pitr=c.begin();pitr!=c.end();++pitr){cout<<*pitr;if(next(pitr,1)!=c.end())cout<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=int>
T in(){T x; cin >> x; return (x);}
template<typename T=int,typename C=vector<T>>
C vecin(int N){C x(N);REP(i,N){x[i]=in<T>();}return move(x);}

void vout(){cout << endl;}
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){cout << ' ' << h;vout(forward<Tail>(t)...);}
void out(){cout << endl;}
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){cout << h;vout(forward<Tail>(t)...);}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	int A,B,C,D,E,F;
	cin>>A>>B>>C>>D>>E>>F;
	
	set<int> W,S;
	for(int i=1;100*A*i<=F;i++){
		for(int j=0;100*A*i+100*B*j<=F;j++){
			W.emplace(100*A*i+100*B*j);
		}
	}
	for(int i=0;C*i<=F;i++){
		for(int j=0;C*i+D*j<=F;j++){
			S.emplace(C*i+D*j);
		}
	}

	int AW=A*100,AS=0;
	for(auto& x:W){
		for(auto& y:S){
			if(x+y>F || E*x<100*y) continue;
			if((x+y)*AS<(AW+AS)*y){
				AW=x,AS=y;
			}
		}
	}
	out(AW+AS,AS);
	return 0;
}


Measured memory_bytes: 384
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <climits>
#include <ctime>
#include <cassert>
using namespace std;

#define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++)
#define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++)
#define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--)
#define all(v) begin(v), end(v)
#define pb(a) push_back(a)
#define fr first
#define sc second
#define INF 2000000000
#define int long long int

#define X real()
#define Y imag()
#define EPS (1e-10)
#define EQ(a,b) (abs((a) - (b)) < EPS)
#define EQV(a,b) ( EQ((a).X, (b).X) && EQ((a).Y, (b).Y) )
#define LE(n, m) ((n) < (m) + EPS)
#define LEQ(n, m) ((n) <= (m) + EPS)
#define GE(n, m) ((n) + EPS > (m))
#define GEQ(n, m) ((n) + EPS >= (m))

typedef vector<int> VI;
typedef vector<VI> MAT;
typedef pair<int, int> pii;
typedef long long ll;

typedef complex<double> P;
typedef pair<P, P> L;
typedef pair<P, double> C;

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

namespace std {
    bool operator<(const P& a, const P& b) {
        return a.X != b.X ? a.X < b.X : a.Y < b.Y;
    }
}

signed main() {
    int n;
    while(cin >> n) {
        if(!n) break;
        int w, h, x, y, s, t; cin >> w >> h;
        int board[110][110] = {};
        rep(i,0,n) {
            cin >> y >> x;
            board[x][y]++;
        }

        cin >> t >> s;
        repq(i,1,h) repq(j,0,w) board[i][j] += board[i-1][j];
        repq(j,1,w) repq(i,0,h) board[i][j] += board[i][j-1];

        /*
        repq(i,1,h) {
            repq(j,1,w) printf("%4d", board[i][j]);
            cout << endl;
        }
        */

        int ma = 0;
        repq(i,1,h-s+1) repq(j,1,w-t+1) {
            int i2 = i+s-1, j2 = j+t-1;
            int temp = board[i2][j2] - board[i-1][j2] - board[i2][j-1] + board[i-1][j-1];
            ma = max(temp, ma);
        }
        cout << ma << endl;
    }
    return 0;
}

Measured memory_bytes: 3180
#include<iostream>
#include<vector>
#include<math.h>
#include<map>
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<functional>
using namespace std;
#define INF int(1e9)
#define N 50
#define MP make_pair
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,a) for(int i=0;i<(a);++i)
typedef pair<int, int> P;
typedef pair<pair<P, P>, P>PP;
typedef long long LL;
LL n, sum;
LL a[N];
vector<LL> sm, bi;
bool judge()
{
	REP(i, n)
		if (a[i] > n - 1)
			return false;
	return true;
}
int solve(LL ans)
{
	LL sum = 0, s;
	REP(i, n)
	{
		s = a[i] / n;
		sum += s;
		a[i] %= n;
		a[i] -= s;
	}
	REP(i, n)
	{
		a[i] += sum;
	}
	judge() ? printf("%lld\n", ans + sum) : solve(ans + sum);
}
int main()
{
	cin >> n;
	REP(i, n)
		cin >> a[i];
	sort(a, a + n);
	judge() ? printf("0\n") : solve(0);
	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;


#define ff              first
#define ss              second
#define int             long long
#define pb              push_back
#define mp              make_pair
#define pii             pair<int,int>
#define vi              vector<int>
#define mii             map<int,int>
#define pqb             priority_queue<int>
#define pqs             priority_queue<int,vi,greater<int> >
#define setbits(x)      __builtin_popcountll(x)
#define zrobits(x)      __builtin_ctzll(x)
#define mod             1000000007
#define inf             1e18
#define ps(x,y)         fixed<<setprecision(y)<<x
#define mk(arr,n,type)  type *arr=new type[n];
#define w(x)            int x; cin>>x; while(x--)
mt19937                 rng(chrono::steady_clock::now().time_since_epoch().count());

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds;


void d_m_c()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
}

int power(int n, int x)
{
	if (x == 0)
		return 1;

	int small = power(n, x / 2) % mod;
	small = (small * small) % mod;

	if (1 & x)
		small = (n * small) % mod;

	return small;
}

bool isPowerOfTwo(int n)
{
	return n && (!(n & (n - 1)));
}

int dp[3001][3001];
int sums[3001][3001];

int solve(int *a, int i, int j)
{
	if (i == j)
		return 0;
	if (dp[i][j] != -1)
		return dp[i][j];

	int minCost = inf;

	for (int k = i; k < j; k++)
	{
		minCost = min(minCost, solve(a, i, k) + solve(a, k + 1, j) + sums[i][j]);
	}

	return dp[i][j] = minCost;
}

void preProcess(int *a, int n)
{
	for (int i = 1; i <= n; i++)
	{
		for (int j = i; j <= n; j++)
			sums[i][j] = a[j] + ((i == j) ? 0 : sums[i][j - 1]);
	}
}


int32_t main()
{
	//d_m_c();

	int n;
	cin >> n;

	int a[n + 1];

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

	memset(dp, -1, sizeof dp);


	cout << solve(a, 1, n) << endl;

	return 0;
}

Measured memory_bytes: 80128