akhauriyash/Code-Regression huggingface dataset:
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1005;
typedef long long ll;
template <typename T> void chkmax(T &x, T y) {x = max(x, y); }
template <typename T> void chkmin(T &x, T y) {x = min(x, y); } 
template <typename T> void read(T &x) {
	x = 0; int f = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
	for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
	x *= f;
}
int n, m, s, a[MAXN];
int x, y, cur[MAXN], res[MAXN], ans[MAXN];
bool cnp(int s, int t) {
	if ((a[s] == x) == (a[t] == x)) return s < t;
	else return (a[s] == x) < (a[t] == x);
}
void work(int len) {
	bool valid = true, found = false;
	for (int i = 1; i <= len; i++)
		a[cur[i]]--;
	int Min = a[1], Max = a[1];
	for (int i = 2; i <= n; i++) {
		chkmin(Min, a[i]);
		chkmax(Max, a[i]);
	}
	if (Min * 2 >= Max) {
		found = true;
		for (int i = 1; i <= len; i++)
			res[i] = cur[i];
		sort(res + 1, res + len + 1);
	} else if (Min * 2 + 1 == Max) {
		x = Min, y = Max;
		int k1 = 0, k2 = 0, k = 0;
		static int res1[MAXN], res2[MAXN];
		for (int i = 1; i <= len; i++)
			if (a[cur[i]] == Min || a[cur[i]] == Max) res1[++k1] = cur[i];
			else res2[++k2] = cur[i];
		sort(res1 + 1, res1 + k1 + 1, cnp);
		sort(res2 + 1, res2 + k2 + 1);
		int x1 = 1, x2 = 1;
		for (int i = 1; i <= len; i++)
			if (x1 <= k1 && x2 <= k2) {
				if (res1[x1] < res2[x2]) res[i] = res1[x1++];
				else res[i] = res2[x2++];
			} else {
				if (x1 <= k1) res[i] = res1[x1++];
				else res[i] = res2[x2++];
			}
		found = true;
		for (int i = len + 1; i <= n; i++)
			if (a[cur[i]] == Min) found = false;
		//found |= (x1 == 0) || (a[res1[1]] == Max);
	}
	for (int i = 1; i <= len; i++)
		a[cur[i]]++;
	if (!valid || !found) res[1] = 0;
}
bool cmp(int *a, int *b) {
	int pos = 1;
	while (a[pos] == b[pos]) pos++;
	return a[pos] < b[pos];
}
bool check() {
	int Min = a[1], Max = a[1];
	for (int i = 2; i <= n; i++) {
		chkmin(Min, a[i]);
		chkmax(Max, a[i]);
	}
	return Min * 2 >= Max;
}
int main() {
	read(n);
	for (int i = 1; i <= n; i++) {
		read(a[i]);
		s += a[i];
	}
	if (!check()) {
		puts("-1");
		return 0;
	}
	for (int i = 1; i <= n; i++)
		cur[i] = i;
	work(n);
	for (int i = 1; i <= n; i++) {
		m++, a[res[i]]--;
		cur[i] = res[i];
		ans[m] = res[i];
	}
	while (m != s) {
		static int inc[MAXN];
		memset(inc, 0, sizeof(inc));
		int len = 0; inc[1] = n + 1;
		for (int i = 1; i <= n; i++) {
			work(i);
			if (res[1] != 0 && cmp(res, inc)) {
				len = i;
				for (int j = 1; j <= i; j++)
					inc[j] = res[j];
			}
		}
		for (int i = 1; i + len <= n; i++)
			cur[i] = cur[i + len];
		for (int i = 1; i <= len; i++) {
			ans[++m] = inc[i];
			cur[n - len + i] = inc[i], a[inc[i]]--;
		}
	}
	for (int i = 1; i <= m; i++)
		printf("%d ", ans[i]);
	printf("\n");
	return 0;
}


Measured memory_bytes: 3828
from collections import deque

N, M = map(int,input().split())

adj = [[] for _ in range(N)]
for i in range(M):
    a,b = map(int,input().split())
    adj[a-1].append(b-1)
    adj[b-1].append(a-1)

is_reachable = True

d = deque()
is_visited = [False] * N
rooms = [-1] * N
distance = [0] * N

d.append(0)
is_visited[0] = 1

while (d):
    v = d.popleft()

    for u in adj[v]:
        if is_visited[u]:
            continue

        is_visited[u] = 1
        rooms[u] = v+1
        distance[u] = distance[v] + 1
        d.append(u)

for i in range(1, N):
    d1 = distance[i]
    sign1 = rooms[i]-1
    if d1 <= distance[sign1]:
        is_reachable = False

if is_reachable:
    print("Yes")
    print(*rooms[1:], sep="\n")
else:
    print("No")

Measured memory_bytes: 40008
#include<stdio.h>
int main()
{
	int n;
	scanf("%d", &n);
	int i;
	long long int t[100005];
	for (i = 0; i < n; i++)
		scanf("%lld", &t[i]);
	long long int a[100005];
	for (i = 0; i < n; i++)
		scanf("%lld", &a[i]);
	long long int h[100005], v[100005];
	for (i = 0; i < n; i++)
		v[i] = 0;
	v[0] = 1;
	h[0] = t[0];
	for (i = 1; i < n; i++)
	{
		if (t[i - 1] < t[i])
		{
			v[i] = 1;
			h[i] = t[i];
		}
		else
			h[i] = h[i - 1];
	}
	if (v[n - 1] == 1 && h[n - 1] != a[n - 1])
	{
		printf("0\n");
		return 0;
	}
	if (v[n - 1] == 0 && h[n - 1] < a[n - 1])
	{
		printf("0\n");
		return 0;
	}
	v[n - 1] = 1;
	h[n - 1] = a[n - 1];
	for (i = n - 2; i >= 0; i--)
	{
		if (v[i] == 0)
		{
			if (a[i + 1] < a[i])
			{
				if (h[i] < a[i])
				{
					printf("0\n");
					return 0;
				}
				v[i] = 1;
				h[i] = a[i];
			}
			else
			{
				if (a[i] < h[i])
					h[i] = a[i];
			}
		}
		else
		{
			if (a[i + 1] < a[i])
			{
				if (a[i] != h[i])
				{
					printf("0\n");
					return 0;
				}
			}
			else
			{
				if (a[i] < h[i])
				{
					printf("0\n");
					return 0;
				}
			}
		}
	}
	long long int ans = 1;
	long long int p = 1000000007;
	for (i = 0; i < n; i++)
		if (v[i] == 0)
			ans = ans * h[i] % p;
	printf("%lld\n", ans);
	return 0;
}

Measured memory_bytes: 3328
#include<stdio.h>

int main(){
  int cnt[100002]={},n,i,a,max=0;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d",&a);
    if(a>1)
      cnt[a-1]++;
    cnt[a]++;
    cnt[a+1]++;
  }
  for(i=0;i<100000;i++){
    if(max<cnt[i])
      max=cnt[i];
  }
  printf("%d\n",max);
}
    

Measured memory_bytes: 512
from collections import defaultdict
N, *A = map(int, open(0).read().split())
ans = 0
A.sort()
dic = defaultdict(list)
for i, a in enumerate(A):
  dic[a] += [i]
for i in range(N-1,-1,-1):
  a = A[i]
  if dic[a]==[]:
    continue
  dic[a].pop()
  k = 1
  while k<=a:
    k *= 2
  n = k-a
  if dic[n]!=[]:
    dic[n].pop()
    ans += 1
print(ans)


Measured memory_bytes: 127896
#include<stdio.h>


int selectionSort(int A[],int N){
	int i,j,t,sw=0,mini;
	for(i=0;i<N-1;i++){
		mini=i;
		for(j=i;j<N;j++){
			if(A[j]<A[mini])mini=j;
		}
		t=A[i];A[i]=A[mini];A[mini]=t;
		if(i!=mini)sw++;
	}
	return sw;
}

int main(){
	int A[100],N,i,sw;
	
	scanf("%d",&N);
	for(i=0;i<N;i++)scanf("%d",&A[i]);
	
	sw=selectionSort(A,N);
	
	for(i=0;i<N;i++){
		if(i>0)printf(" ");
		printf("%d",A[i]);
	}
	printf("\n");
	printf("%d\n",sw);
	
	return 0;
}

Measured memory_bytes: 604
#pragma GCC optimize ("O2")
#pragma GCC target ("avx")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

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


	int T;
	cin >> T;

	rep(k, T) {
		int N;
		cin >> N;
		ll A[200];
		rep(j, N) cin >> A[j];
		string S;
		cin >> S;

		ll B[62] = {};
		int dame = 0;
		for (int i = N - 1; i >= 0; i--) {
			ll a = A[i];
			if (S[i] != '1') {
				for (int j = 60; j >= 0; j--) {
					if (a >> j & 1) {
						if (B[j]) a ^= B[j];
						else {
							B[j] = a;
							break;
						}
					}
				}
			}
			else {
				for (int j = 60; j >= 0; j--) {
					if (a >> j & 1) {
						if (B[j]) a ^= B[j];
						else {
							dame = 1;
							break;
						}
					}
				}
			}
		}

		if (dame) co(1);
		else co(0);
	}


	Would you please return 0;
}

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

int main() {
  int H,W,N;
  cin >> H >> W >> N;
  if(N%max(H,W)==0) cout << N/max(H,W) << endl;
  else cout << N/max(H,W)+1 << endl;
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define UNIQUE(v) v.erase(unique(all(v)), v.end());
#define ZIP(v) sort(all(v)),UNIQUE(v)
#define ADD(a, b) a = (a + b) % mod
#define SUB(a, b) a = (a+mod-b)%mod
#define MUL(a, b) a = (a * b) % mod
#define repi(i,m,n) for(int i = m;i < n;i++)
#define drep(i,n,m) for(int i = n;i >= m;i--)
#define rep(i,n) repi(i,0,n)
#define rrep(i,n) repi(i,1,n+1)
#define chmin(x,y) x = min(x,y)
#define chmax(x,y) x = max(x,y)
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(), v.rend()
#define dmp(x,y) make_pair(x,y)
#define pb(x) push_back(x)
#define fi first
#define se second
typedef pair<int,int> P;
typedef pair<int, P> PP;
typedef pair<P, int> Pi;
typedef vector<int> vi;
typedef deque<int> dq;
const int inf = 1e9+7;
const int INF = 1e18+7;

char c[1000][1000];
int a[1000][1000], b[1000][1000];
signed main(){
	int h, w;
	scanf("%lld%lld", &h, &w);
	rep(i,h){
		string str;
		cin >> str;
		rep(j,w)c[i][j] = str[j];
	}
	rep(i,h)rep(j,w){
		if(i%2){
			if(j == w-1)b[i][j] = 1;
			else a[i][j] = 1;
		}else{
			if(j == 0)a[i][j] = 1;
			else b[i][j] = 1;
		}
	}
	rep(i,h)rep(j,w){
		if(c[i][j] == '#')a[i][j] = b[i][j] = 1;
	}
	
	rep(i,h){
		rep(j,w)printf("%c", a[i][j] ? '#' : '.');
		printf("\n");
	}
	rep(i,h){
		rep(j,w)printf("%c", b[i][j] ? '#' : '.');
		printf("\n");
	}
	return 0;
}







Measured memory_bytes: 13056
import math
a,b,h,m = map(int,input().split())
h1 = ((h+m/60)/12)*360
m1 = m/60*360

x = min(abs(h1-m1),360-(abs(h1-m1)))

c = a**2+b**2-2*a*b*math.cos(math.radians(x))
print(c**0.5)


Measured memory_bytes: 9564
n = int(input())
a = list(map(int,input().split()))
import numpy as np
a=np.array(a)
mod = 10**9+7
md = len(bin(max(a)))
ans = 0
for d in range(md):
    cnt1 = np.count_nonzero((a>>d)&1)# a内の全ての要素の d bit目の1の個数を数える
    ans += cnt1 * (n-cnt1) * (1<<d)          # 求めるべきは (0の個数)*(1の個数)をd bit目にそのまま収めたものを足し合わせたもの (?)
    ans %= mod                               # mod 取っておく
    
print(ans%mod)

Measured memory_bytes: 44204
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int> e[N];
queue<int> Q;
int n,deg[N];
bool del[N],white[N];
void erase(int x){
	del[x]=1;
	for (int i=0;i<e[x].size();i++){
		int v=e[x][i];
		if (del[v]) continue;
		deg[v]--;
		if (deg[v]==0) puts("First"),exit(0);
		if (deg[v]==1) Q.push(v);
	}
}
int main()
{
	scanf("%d",&n);
	for (int i=1;i<n;i++){
		int u,v;
		scanf("%d%d",&u,&v);
		e[u].push_back(v);
		e[v].push_back(u);
		deg[u]++;deg[v]++;
	}
	for (int i=1;i<=n;i++)
		if (deg[i]==1) Q.push(i);
	while (!Q.empty()){
		int v=Q.front();Q.pop();
		del[v]=1;
		for (int i=0;i<e[v].size();i++){
			int u=e[v][i];
			if (del[u]) continue;
			erase(u);
		}
	}
	puts("Second");
	return 0;
}

Measured memory_bytes: 6400
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 counter = 0;
    
    for (String s : s2) {
      if (s.equals("1"))
          counter ++;
    }
    System.out.println(counter);
  }
}

Measured memory_bytes: 22996
// #pragma GCC optimize("Ofast")
// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
// #pragma GCC optimize("unroll-loops")

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define DEBUG
#ifdef DEBUG
#define debug(...) __f(#__VA_ARGS__, __VA_ARGS__)
	template <typename Arg1>
	void __f(const char* name, Arg1&& arg1)
	{
		cerr << name << " = " << arg1 << endl;
	}
	template <typename Arg1, typename... Args>
	void __f(const char* names, Arg1&& arg1, Args&&... args)
	{
		const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << " = " << arg1 << " || ";
		__f(comma+1, args...);
	}
#else
#define debug(...)
#endif

template <class Ch, class Tr, class Container>
basic_ostream <Ch, Tr> & operator << (basic_ostream <Ch, Tr> & os, Container const& x) {
    os << "{ ";
    for(auto& y : x) os << y << " ; ";
    return os << "}";
}

template <class X, class Y>
ostream & operator << (ostream & os, pair <X, Y> const& p) {
	return os << "[ " << p.first << ", " << p.second << "]" ;
}

#define FAST_IO std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define ll long long int
#define pb push_back
#define mp make_pair
#define ld long double
#define sz(a) (ll)(a).size()
#define endl "\n"

// priority_queue<ll, vector<ll>, less<ll>>pq;     // Max Heap
// priority_queue<ll, vector<ll>, greater<ll>>pq;  // Min Heap

typedef tree<ll,null_type,less<ll>,rb_tree_tag,tree_order_statistics_node_update> ordered_set;
//K-th smallest
//cout << k << "kth (1 based indexing) smallest: " << *A.find_by_order(k - 1) << endl;
//NO OF ELEMENTS < X
//cout << "No of elements less than " << X << " are " << A.order_of_key(X) << endl;

int main()
{
	FAST_IO;

 	ll n, ans = -1e18;
 	cin >> n;
 	ll a[3*n], fr[3*n], ba[3*n];
 	multiset<ll>s;
 	for(int i=0;i<3*n;i++) cin >> a[i];
 	for(int i=0;i<3*n;i++)
 	{
 		if(sz(s) < n) 
 		{	
 			s.insert(a[i]);
 			if(i > 0) fr[i] = fr[i - 1] + a[i];
 			else fr[i] = a[i];
 		}
 		else
 		{
 			ll w = *s.begin();
 			fr[i] = fr[i - 1];
 			if(w >= a[i]) continue;
 			else
 			{
 				s.insert(a[i]);
 				s.erase(s.find(w));
 				fr[i] += a[i] - w;
 			}
 		}	
 	}
 	multiset<ll, greater<ll>>s1;
 	for(int i=3*n-1;i>=0;i--)
 	{
 		if(sz(s1) < n) 
 		{	
 			s1.insert(a[i]);
 			if(i < 3 * n - 1) ba[i] = ba[i + 1] + a[i];
 			else ba[i] = a[i];
 		}
 		else
 		{
 			ll w = *s1.begin();
 			ba[i] = ba[i + 1];
 			if(w <= a[i]) continue;
 			else
 			{
 				s1.insert(a[i]);
 				s1.erase(s1.find(w));
 				ba[i] += a[i] - w;
 			}
 		}	
 	}
 	for(int i=0;i<3*n;i++)
 	{
 		if(i >= n && i <= 2 * n)
 			ans = max(ans, fr[i - 1] - ba[i]);
 	}
 	cout << ans << endl;
    return 0;
}

Measured memory_bytes: 20016
#include <string>
#include <iostream>
#include <cmath>
using namespace std;

#define rep(i,a,b) for(auto (i)=a;i<b;i++)
#define list(i,N) for(auto (i)=0;i<N;i++)

typedef long long ll;

int main(){

	ios_base::sync_with_stdio(0);
	cin.tie(0);

	int N; cin >> N;
	string S; cin >> S;
	string T; cin >> T;
	string newString = "";
	list(i,N){
		newString += S[i];
		newString += T[i];
	}
	cout << newString;
	return 0;
}



Measured memory_bytes: 256
#include<cstdio>
using namespace std;
long long n,x,ans,a,b;
int main()
{
	scanf("%lld%lld",&n,&x);
	ans=n;n=n-x;
	while(x) {
		ans+=n/x*x*2;
		a=n%x;b=x;
		if(!a) ans-=x;
		n=b;x=a;
	}
	printf("%lld",ans);
	return 0;
}

Measured memory_bytes: 128
import math
from functools import reduce


def gcd(numbers):
    return reduce(math.gcd, numbers)


k = int(input())
l = []
res = 0

for i in range(1, k+1):
    for j in range(i, k+1):
        for m in range(j, k+1):
            if i == j and j == m:
                res += gcd([i, j, m])
            elif i == j or j == m or i == m:
                res += gcd([i, j, m])*3
            else:
                res += gcd([i, j, m])*6
print(res)


Measured memory_bytes: 9624
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<int,int> pint;

int main(){
    int n;
    while(cin>>n && n){
        vector<pint> tget;
        vector<int> chars;
        int c,count;
        int tmp=0;
        for(int i=0;i<n;++i){
            cin>>c;
            chars.push_back(c);
        }
        int maxsum=0;
        for(int i=1;i<n-1;++i){
            int curb=i,curf=i;
            int color=chars[i-1];
            int dsum=0;
            int back=1,forwd=0;            
            while(true){                
                while(curb-back>=0&&chars[curb-back]==color) ++back;
                while(curf+forwd<n-1&&chars[curf+forwd+1]==color) ++forwd;
                if(back+forwd<4) break;
                dsum += back + forwd;                
                curb -= back;curf += forwd;color=chars[curb];
                back=0;forwd=0;
            }
            maxsum=max(maxsum,dsum);
        }
        cout<<chars.size()-maxsum<<endl;
    }
    return 0;
}

Measured memory_bytes: 3188
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break

N = list(get_input())

for l in range(len(N)):
    n = int(N[l])
    print("3C", end="")
    ans = n % 39
    if ans == 0:
        print(39)
    elif ans < 10:
        print("0", end="")
        print(ans)
    else:
        print(ans)





Measured memory_bytes: 5596
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define ALL(a)  (a).begin(),(a).end()
#define SUM(a)  accumulate((a).begin(),(a).end(),0)
#define SORT(a) sort(ALL(a))
#define REV(a) reverse(ALL(a))
#define dump(x)  cerr << #x << " = " << (x) << endl;
typedef long long ll;
const int INTINF = 1<<29;
const ll LLINF = 1LL<<61;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;
const int DX[8]={ 0, 1, 0,-1, 1, 1,-1,-1};
const int DY[8]={ 1, 0,-1, 0, 1,-1, 1,-1};

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  int n,k,x,y;
  cin >> n >> k >> x >> y;

  cout << min(n,k)*x + max(0,n-k)*y << endl;
}

Measured memory_bytes: 256
// 2020-07-25 07:27:17
#include<bits/stdc++.h>
#ifdef LOCAL
#include "lib/debug.hpp"
#else
#define debug(...) 1
#endif
#define ALL(a) (a).begin(), (a).end()
#define rep(i, n) REP(i, 0, (n))
#define repc(i, n) REPC(i, 0, (n))
#define REP(i, n, m) for (int i = (int)(n); i < (int)(m); i++)
#define REPC(i, n, m) for (int i = (int)(n); i <= (int)(m); i++)
#define REPCM(i, n, m) for (int i = (int)(n); i >= (int)(m); i--)
using namespace std;
using ll = long long;
using ld = long double;
using pr = pair<ll, ll>;
using vll = vector<ll>;
using vpr = vector<pr>;
using P = pair<int, int>;
template<class T> inline bool chmin(T& a, const T& b) { if (a > b) { a = b; return true; } else return false; }
template<class T> inline bool chmax(T& a, const T& b) { if (a < b) { a = b; return true; } else return false; }

void answer() {
  int n, k;
  cin >> n >> k;
  vector<int> a(n+1, 0);
  rep(i, n) {
    cin >> a[i+1];
    a[i+1]--;
  }
  map<int, vector<int> > mp;
  int cur = 0;
  repc(i, n) {
    cur = (cur + a[i]) % k;
    mp[cur].push_back(i);
  }
  ll ans = 0;
  for(auto p : mp) {
    auto& v = p.second;
    int sz = v.size();
    int l = 0, r = 0;
    while(l < sz) {
      while(r < sz && v[r] - v[l] < k) {
        r++;
      }
      ans += r - l - 1;
      l++;
    }
  }
  cout << ans << '\n';
}
int main() {
  std::ios::sync_with_stdio(false);
  std::cin.tie(0);
  answer();
  return 0;
}

Measured memory_bytes: 25824
n = int(input())
h = [int(i) for i in input().split()]

#DPテーブルの初期化
cost = [float("inf") for i in range(n)]
cost[:2] = 0, abs(h[0]-h[1])

#ループ
for i in range(2, n):
    tmp1 = cost[i-1] + abs(h[i]-h[i-1])
    tmp2 = cost[i-2] + abs(h[i]-h[i-2])
    cost[i] = min(tmp1, tmp2)

#解答
print(cost[-1])

Measured memory_bytes: 13924
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define F first
#define S second
#define pii pair<int, int>
#define eb emplace_back
#define all(v) v.begin(), v.end()
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rep3(i, l, n) for (int i = l; i < (n); ++i)
#define sz(v) (int)v.size()
#define inf (int)(1e9+7)
#define INF (ll)(1e18)
#define abs(x) (x >= 0 ? x : -(x))
#define ceil(a, b) a / b + !!(a % b)
template<typename T1, typename T2> inline bool chmin(T1 &a, T2 b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T1, typename T2> inline bool chmax(T1 &a, T2 b) { if (a < b) { a = b; return 1; } return 0; }
template<typename T> T gcd(T a, T b) { if (b == 0) return a; return gcd(b, a % b); }
template<typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; }

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    
    int n;
    cin >> n;
    int cnt = 0;
    int now = 1;
    rep(i, n) {
        int a;
        cin >> a;
        if (a == now) {
            now++;
        } else {
            cnt++;
        }
    }
    // cout << cnt << endl;
    cout << (cnt == n ? -1 : cnt) << endl;
}


Measured memory_bytes: 256
//**************************
//*** author  :  Alex Hu **
//************************

//  _______        __________         ________        __
//  \      \   ____\______   \ ____  /  _____/  _____/  |_
//  /   |   \ /  _ \|       _// __ \/   \  ____/ __ \   __\
// /    |    (  <_> )    |   \  ___/\    \_\  \  ___/|  |
// \____|__  /\____/|____|_  /\___  >\______  /\___  >__|
//         \/              \/     \/        \/     \/

#include<bits/stdc++.h>

using namespace std;

#define CLEAN(a,b) memset(a,b,sizeof(a))
#define mkp make_pair
#define pb push_back
#define rept(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define fi first
#define se second
#define sqr(a) ((a)*(a))

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

const ll mod=1e9+7;
const ll INF=0x3f3f3f3f3f3f3f3f;

int cnt[50];

int main(){
	for(int i=0;i<3;i++){
		int a,b;
		cin>>a>>b;
		cnt[a]++;cnt[b]++;
	}
	if(*max_element(cnt+1,cnt+5)>2){
		puts("NO");
	}else{
		puts("YES");
	}
	return 0;
}


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

    using namespace std;
    using namespace std::chrono; 

    typedef long long int ll;

    #define MOD (ll)(1e9+7)
    #define endl "\n"
    #define pb push_back
    #define TEST_CASES  ll t;cin>>t;while(t--)
    #define forn(i,a,n) for (int i = a; i < n; ++i)
    #define f first
    #define s second
    #define all(x) x.begin(), x.end()

    void __print(int x) {cerr << x;}
    void __print(long x) {cerr << x;}
    void __print(long long x) {cerr << x;}
    void __print(unsigned x) {cerr << x;}
    void __print(unsigned long x) {cerr << x;}
    void __print(unsigned long long x) {cerr << x;}
    void __print(float x) {cerr << x;}
    void __print(double x) {cerr << x;}
    void __print(long double x) {cerr << x;}
    void __print(char x) {cerr << '\'' << x << '\'';}
    void __print(const char *x) {cerr << '\"' << x << '\"';}
    void __print(const string &x) {cerr << '\"' << x << '\"';}
    void __print(bool x) {cerr << (x ? "true" : "false");}

    template<typename T, typename V>
    void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
    template<typename T>
    void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
    void _print() {cerr << "]\n";}
    template <typename T, typename... V>
    void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
    #ifndef ONLINE_JUDGE
    #define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
    #else
    #define debug(x...)
    #endif

    ll powD(ll x,ll y){
      ll res = 1;
      while(y > 0){
        if(y & 1)
          res = (res*x)%MOD;
        x = (x*x)%MOD;
        y = y>>1;
      }
      return res;
    }

    /*CHECK FOR CORNER CASES FOR GOD'S SAKE*/
    int main()
    {
      //freopen("dislodging_logs_validation_input.txt", "r", stdin);
      //freopen("output.txt", "w", stdout);
      ios_base::sync_with_stdio(false);
      cin.tie(NULL);
      int n,k,t;
      cin>>n>>k>>t;
      int ans = (n/k + (n%k != 0))*t;
      cout<<ans<<endl;
  } 



     
    


Measured memory_bytes: 3640
#include<iostream>
#include<stdio.h>

using namespace std;

int main()
{
  int n;
  char s[100];
  cin>>n;
  
  for(int i=0;i<n;i++){
    cin>>s[i];
  }
  
  int a=0;
  if(n%2==1)a=1;
   for(int i=0;i<n/2;i++){
     if(s[i]!=s[i+n/2]){
       a=1;
       break;
     }
  }
   if(a==1)
   cout<<"No"<<endl;
   else
     cout<<"Yes"<<endl;
  
  return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <cmath>
using namespace std;
#define ll long long
ll rnum, bnum;
ll num[3];
int main() {
    int i = 0;
    for(;i < 3; ++i)cin >> num[i];
    ll mn = 1e19;
    for(i = 0; i < 3; ++i){
        rnum = num[i%3]/2 * num[(i+1)%3] * num[(i+2)%3];
        bnum = (num[i%3] - num[i%3]/2) * num[(i+1)%3] * num[(i+2)%3];
        mn = min(llabs(rnum - bnum), mn);
    }
    cout << mn << endl;
    return 0;
}


Measured memory_bytes: 256
N=int(input())
ARRAY=[list(map(int,input().split())) for i in range(N)]

dp=[[0,0,0] for i in range(N+1)]

for i in range(1,N+1):
    #print("l")
    dp[i][0]=ARRAY[i-1][0]+max(dp[i-1][1],dp[i-1][2])
    dp[i][1]=ARRAY[i-1][1]+max(dp[i-1][0],dp[i-1][2])
    dp[i][2]=ARRAY[i-1][2]+max(dp[i-1][1],dp[i-1][0])

print(max(dp[N]))





Measured memory_bytes: 47384
#include<bits/stdc++.h>
#define ll          long long int
#define pb          push_back
#define mpp         make_pair
#define vll         vector<ll>
#define mll         unordered_map<ll,ll>
#define endl        "\n"
#define debug(x)    cout<< #x <<"="<<x<<"\n"
#define fo(i,a,x)   for(ll i=a;i<x;++i)
#define fastio      ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;

ll n,m,k;

void solve()
{
    float d,t,s;
     cin>>d>>t>>s;
     if(fabs((d/s)-t) <= 1e-9 || (t-(d/s))>=0)
     {
        cout<<"Yes"<<endl;
     }
     else cout<<"No"<<endl;
}

int main()
{
    fastio;
    // #ifndef ONLINE_JUDGE
    //     freopen("input.txt", "r", stdin);
    //     freopen("output.txt", "w", stdout);
    // #endif
    ll t=1; 
    // cin>>t;
    while(t--)
    {
        solve();
    }
    return 0;
}

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

template<typename T> T gcd(T a, T b) { return b ? gcd(b, a%b) : a; }
template<typename T> T lcm(T a, T b) { return a / gcd(a, b) * b; }
template<class T> void corner(bool flg, T hoge) { if (flg) { cout << hoge << endl; exit(0); } }

const int MOD = 1000000007;

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

    int a, b, c, d;
    a = s[0] - '0';
    b = s[1] - '0';
    c = s[2] - '0';
    d = s[3] - '0';

    for (int i = 0; i < 8; i++) {
        int total = a;
        total += ((i >> 2) & 1) ? -b : b;
        total += ((i >> 1) & 1) ? -c : c;
        total += ((i >> 0) & 1) ? -d : d;
        if (total == 7) {
            string res = "";
            res += s[0];
            if ((i >> 2) & 1) res += "-";
            else res += "+";
            res += s[1];
            if ((i >> 1) & 1) res += "-";
            else res += "+";
            res += s[2];
            if ((i >> 0) & 1) res += "-";
            else res += "+";
            res += s[3];
            res += "=7";
            cout << res << endl;
            break;
        }
    }
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<string>
using namespace std;
typedef long long ll;
#define endl '\n';

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll n;
    cin >> n;
    
    ll ac = 0;
    ll wa = 0;
    ll tle = 0;
    ll re = 0;
    while(n--)
    {
        string s;
        cin >> s;
        if(s == "AC")
        {
            ac++;
        }
        else if(s == "WA")
        {
            wa++;
        }
        else if(s == "TLE")
        {
            tle++;
        }
        else if(s == "RE")
        {
            re++;
        }
    }
    
    cout << "AC x " << ac << endl;
    cout << "WA x " << wa << endl;
    cout << "TLE x " << tle << endl;
    cout << "RE x " << re;
    return 0;
}

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

int n, k, x[101], ans;
int main(){
	cin >> n >> k;
	for(int i=0;i<n;i++){
		cin >> x[i];
		ans += min(2*x[i], 2*k - 2*x[i]);
	}
	cout << ans << endl;
	return 0;
}

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

public class Test
{
	public static void Main()
	{
		// your code goes here
		
		var hoge = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray();
		
		int a = hoge[0];
		int b = hoge[1];
		
		if(a<=5){
			Console.WriteLine("0");
		}else if(a<=12){
			Console.WriteLine(b/2);
		}else{
			Console.WriteLine(b);
		}
		
	}
}

Measured memory_bytes: 13268
from collections import Counter

N = int(input())
pf={}

for i in range(2,int(N**0.5)+1):
    while N%i==0:
        pf[i]=pf.get(i,0)+1
        N//=i
if N>1:pf[N]=1

value_ = Counter(list(pf.values()))
result = 0
for k,v in value_.items():
    if k == 1:
        result += v
    else:
        for i in range(k+1):
            if i * (i+1) / 2 > k:
                result += (i-1) * v
                break
print(result)


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

int n,q;
string w[100010];

template<int char_size>
struct Trie{
	struct Node{
		int nxt[char_size];
 
		int childs;
		bool isExist;
 
		Node() : childs(0),isExist(false){
			fill(nxt,nxt + char_size,-1);
		}
	};
 
	static inline int ctoi_default(char c){
		return c - 'a';
	}
 
	using F = function<int(char)>;
	F ctoi;
	vector<Node> nodes;
 
	Trie(F ctoi = ctoi_default) : ctoi(ctoi){
		nodes.emplace_back();
	}
 
	inline int &next(int pos,int c){
		return nodes[pos].nxt[c];
	}
 
	inline int &next(int pos,char c){
		return next(pos,ctoi(c));
	}
 
	void add(const string &s){
		int pos = 0;
		for(int i = 0;i < s.length();i++){
			const int c = ctoi(s[i]);
			if(next(pos,c) == -1){
				next(pos,c) = nodes.size();
				nodes.emplace_back();
			}
			pos = next(pos,c);
			nodes[pos].childs++;
		}
		nodes[pos].isExist = true;
	}
 
	int find(const string &s){
		int pos = 0;
		for(int i = 0;i < s.length();i++){
			const int c = ctoi(s[i]);
			if(next(pos,c) == -1) return -1;
			pos = next(pos,c);
		}
		return pos;
	}
};

struct SegTree{
	int n,seg;
	//vector<Trie<26>> trie;
	vector<vector<string>> dat;
	SegTree(int siz) : n(siz),seg(1){
		while(seg < n) seg *= 2;
		dat.resize(seg * 2 - 1);
		//trie.resize(seg * 2 - 1);
		for(int i = 0;i < n;i++){
			string v = w[i];
			reverse(v.begin(),v.end());
			dat[i + seg - 1].push_back(v);
			//trie[i + seg - 1].add(v);
		}
		for(int i = seg - 2;i >= 0;i--){
			dat[i].insert(dat[i].end(),dat[i * 2 + 1].begin(),dat[i * 2 + 1].end());
			dat[i].insert(dat[i].end(),dat[i * 2 + 2].begin(),dat[i * 2 + 2].end());
			sort(dat[i].begin(),dat[i].end());
			//for(const string &s : dat[i]) trie[i].add(s);
		}
	}
	int get(const string &s,int a = 0,int b = -1,int k = 0,int l = 0,int r = -1){
		if(b == -1) b = seg;
		if(r == -1) r = seg;
		if(b <= l || r <= a) return 0;
		if(a <= l && r <= b){
			int lind = lower_bound(dat[k].begin(),dat[k].end(),s) - dat[k].begin();
			string t = s; t.back()++;
			int rind = lower_bound(dat[k].begin(),dat[k].end(),t) - dat[k].begin();
			return rind - lind;
		}
		return get(s,a,b,k * 2 + 1,l,(l + r) / 2) + get(s,a,b,k * 2 + 2,(l + r) / 2,r); //do
	}
};

signed main(){
	cin >> n >> q;
	for(int i = 0;i < n;i++) cin >> w[i];
	sort(w,w + n);
	SegTree seg(n);
	for(int i = 0;i < q;i++){
		string p,s;
		cin >> p >> s;
		reverse(s.begin(),s.end());
		int l = lower_bound(w,w + n,p) - w;
		p.back()++;
		int r = lower_bound(w,w + n,p) - w;
		cout << seg.get(s,l,r) << endl;
	}
}


Measured memory_bytes: 42676
#include <iostream>
#include <algorithm>
//#include <string>

//using namespace std;

int main()
{
    std::string s1, s2, s3; 
    std::cin >> s1 >> s2 >> s3; 

    transform(s1.begin(), s1.end(), s1.begin(), toupper);
    transform(s2.begin(), s2.end(), s2.begin(), toupper);
    transform(s3.begin(), s3.end(), s3.begin(), toupper);

    std::cout << s1.at(0) << s2.at(0) << s3.at(0)<< std::endl;
}

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

int main() {
  string s; cin >> s;
  int n = 0;
  int m = 0;
  for (int i = 0; i < s.size(); i++) {
    if (s.at(i) == 'T') {n--; m = min(m, n);}
    else {n++;}
  }
  cout << -2*m << endl;
}

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

int main() {
	int n, a, b; cin >> n >> a >> b;

	int ans = 0;
	rep(i, 0, n) {
		int num = i + 1, sum = 0, r = 0;
		rep(j, 1, 6) {
			int a = pow(10, j);
			sum += ((num - r) % a) * 10 / a;
			r = ((num - r) % a) * 10 / a;
		}
		if (a <= sum && sum <= b) ans += num;
	}

	cout << ans << endl;

	return 0;
}

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


struct listnode{
 int val;
 listnode*  next;};


int32_t main(){
  int x;
  cin>>x;
  if(x==0)cout<<1<<endl;
  else cout<<0<<endl;

  
return 0;
}

Measured memory_bytes: 3616
#include<cstdio>
#include<algorithm>

std::pair<int, int> s[201], h[1001];
int x, y, m, n;

int main() {

	while (scanf("%d", &m), m != 0) {
		bool ok = true;
		int ansx = 0, ansy = 0;

		for (int i = 0; i < m; i++) {
			scanf("%d%d", &x, &y);
			s[i] = std::make_pair(x, y);
		}
		scanf("%d", &n);
		for (int i = 0; i < n; i++) {
			scanf("%d%d", &x, &y);
			h[i] = std::make_pair(x, y);
		}

		std::sort(h, h + n);

		for (int i = 0; i < n; i++) {
			x = h[i].first - s[0].first;
			y = h[i].second - s[0].second;
			ok = true;
			for (int j = 0; j < m; j++) {
				if (!std::binary_search(h, h + n, std::make_pair(s[j].first + x, s[j].second + y))) {
					ok = false;
				}
			}
			if (ok) {
				ansx = x;
				ansy = y;
				printf("%d %d\n", ansx, ansy);
			}
		}
		//printf("%d %d\n", ansx, ansy);
	}
	return 0;
}


Measured memory_bytes: 2620
#![allow(non_snake_case)]
#[allow(unused_imports)]
use std::io::{self, Write};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
    ($next:expr, char) => {
        read_value!($next, String).chars().collect::<Vec<char>>()[0]
     };
    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
     };
    ($next:expr, isize1) => {
        read_value!($next, isize) - 1
    };
     ($next:expr, $t:ty) => {
         $next().parse::<$t>().expect("Parse error")
    };
}
macro_rules! printvec {
    ( $item:expr ) => {
        for &i in &$item {
            print!("{} ", i);
        }
        println!("");
    }
}
macro_rules! debug {
    ($($a:expr),*) => {
        println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}
#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);
impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}
#[derive(PartialEq, PartialOrd, Clone, Debug)]
pub struct Total<T>(pub T);
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> {
    fn cmp(&self, other: &Total<T>) -> Ordering {
        self.0.partial_cmp(&other.0).unwrap()
    }
}
#[allow(dead_code)]
const MOD: usize = 1000000007;


fn main() {
    input!{
        s1: chars,
        s2: chars,
        s3: chars,
    }
    println!("{}{}{}", s1[0].to_string().to_uppercase(), s2[0].to_string().to_uppercase(), s3[0].to_string().to_uppercase());
}

Measured memory_bytes: 4352
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
#include <time.h>
#include <bits/stdc++.h>

#define IO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
using namespace std;
typedef long long int ll;
int main() {
#ifdef _DEBUG
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    IO;
    int n ;
    cin>>n ;
    int best_a=0,best_b=0,best_c=0;
    int a , b ,c ;
    for(int i =0 ;i < n ; i++){
        cin>>a>>b>>c;
        int t_a=best_a,t_b=best_b,t_c=best_c;
        best_a=max(t_b,t_c)+a;
        best_b=max(t_a,t_c)+b;
        best_c=max(t_a,t_b)+c;
    }
    cout<<max({best_a,best_b,best_c})<<endl;

    return 0;
}

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

int main()
{
        int n, m, l;
        cin >> n >> m >> l;
        int a[n][m];
        int b[m][l];
        for (int i = 0; i < n; ++i) {
                for (int j = 0; j < m; ++j) {
                        int tmp;
                        cin >> tmp;
                        a[i][j] = tmp;
                }
        }
        for (int i = 0; i < m; ++i) {
                for (int j = 0; j < l; ++j) {
                        int tmp;
                        cin >> tmp;
                        b[i][j] = tmp;
                }
        }
        long long c[n][l];
        for (int i = 0; i < n; ++i) {
                for (int j = 0; j < l; ++j) {
                        long long ans = 0;
                        for (int k = 0; k < m; ++k) {
                                ans += (a[i][k] * b[k][j]);
                        }
                        c[i][j] = ans;
                }
        }
        for (int i = 0; i < n; ++i) {
                for (int j = 0; j < l; ++j) {
                        cout << c[i][j];
                        if (j != l-1) {
                                cout << " ";
                        }
                }
                cout << endl;
        }

}



Measured memory_bytes: 3276
R,G,B,N = map(int,input().split())
c = sorted([R,G,B])
R = c[1]
G = c[2]
B = c[0]
ans = 0
for r in range(N//R+1):
    tmp = N - r*R
    for g in range(N//G+1):
        ttmp = tmp - g*G
        ans += (ttmp%B == 0 and ttmp >= 0)
print(ans)

Measured memory_bytes: 9224
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <climits>
#include <iomanip>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
int main(){
  ll n;
  cin >> n;
  vector<ll> a(n);
  vector<ll> b(n);
  for(int i = 0;i < n;i++)cin >> a[i],b[i] = a[i];
  sort(a.begin(),a.end());
  ll k = 0;
  for(int i = 0;i < n;i++){
    if(a[i] != b[i])k++;
  }
  if(k <= 2)cout << "YES" << endl;
  else cout << "NO" << endl;
}

Measured memory_bytes: 3632
from sys import stdin, setrecursionlimit


def main():
    input = stdin.buffer.readline
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))

    ans = 0
    tmp = 0

    for i in range(n):
        if tmp >= a[i]:
            ans += a[i]
            a[i] = 0
        else:
            ans += tmp
            a[i] -= tmp
        if b[i] >= a[i]:
            ans += a[i]
            tmp = b[i] - a[i]
        else:
            ans += b[i]
            tmp = 0

    if tmp >= a[-1]:
        ans += a[-1]
    else:
        ans += tmp

    print(ans)


if __name__ == "__main__":
    setrecursionlimit(10000)
    main()


Measured memory_bytes: 62936
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define rep(i,n) for(int i=0;i<n;i++)
void dfs(vector<int>v[],int i,int vis[],int dp[])
{
    vis[i]=1;
    for(auto x:v[i])
    {
        if(!vis[x])
        dfs(v,x,vis,dp);
        dp[i]=max(dp[i],dp[x]+1);
    }
    
}
int main()
{
    int n,m,x,y;
    cin>>n>>m;
    vector<int>v[n];
    int ma=0;
    rep(i,m)
    {
        cin>>x>>y;
        x--;
        y--;
        v[x].pb(y);
    }
    int vis[n]={0};
    int dp[n]={0};
    rep(i,n)
    {
        if(!vis[i] && v[i].size())
        {
            stack<int>s;
            dfs(v,i,vis,dp);
            
        
        }
        else
        vis[i]=1;
    }
    cout<<*max_element(dp,dp+n);
    
}

Measured memory_bytes: 9856
#include <bits/stdc++.h>
#define aaa cout<<233<<endl;
#define endl '\n'
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
// mt19937 rnd(TM(0));
const int inf = 0x3f3f3f3f;//1061109567 > 1e9
const ll linf = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-6;
const double pi = 3.14159265358979;
const int maxn = 1e5 + 5;
const int maxm = 5e5 + 233;
const int mod = 1e9 + 7;

ll n, a[maxn];
int main()
{
    // double pp = clock();
    // freopen("233.in", "r", stdin);
    // freopen("233.out", "w", stdout);
    ios_base::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    
    cin >> n;
    ll ans = linf;
    for(ll i = 1; i * i <= n; ++i){
        if(n / i * i == n){
            ans = min(ans, i + n / i - 2);
        }
    }
    cout << ans << endl;

    // cout << endl << (clock() - pp) / CLOCKS_PER_SEC << endl;
    return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#include <unordered_set>
#include <stdio.h>

using namespace std;

#define scan(x) do{while((x=getchar())<'0'); for(x-='0'; '0'<=(_=getchar()); x=(x<<3)+(x<<1)+_-'0');}while(0)
char _;
#define f first
#define s second
#define ll long long
#define ull unsigned long long
#define endl "\n"
#define PI 3.141592653589793
#define vi vector<int>
#define vll vector<long long>
#define p pair<int,int>
const ll MOD = 1000000007;
inline double degcos(double ang) {return cos(ang*PI/180);}
inline double degsin(double ang) {return sin(ang*PI/180);}
#define rep(i,j,k,in) for (int i = j; i < k; i += in)


/*---END OF TEMPLATE---*/

int N,K;
ll dp[100005];
ll P[100005];


ll calculate(int stepBack, int cur) {
    if (stepBack < 0) {
        stepBack = 0;
    }
    ll ret = P[cur];
    if (stepBack > 0) ret -= P[stepBack-1];
    return (ret + MOD) % MOD;
}

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

    cin >> N >> K;
    dp[0] = 1;
    rep(var,1,N+1,1) {
        int val;
        cin >> val;
        P[0] = dp[0];
        dp[0] = 0;
        for (ll i = 1; i <= K; i++) {
            P[i] = (P[i-1] + dp[i]) % MOD;
        }
        for (ll i = 0; i <= K; i++) dp[i] = calculate(i-val,i);
    }
    cout << (dp[K] + MOD) % MOD;
}




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

using namespace std;
#define ll long long
#define ull unsigned long long
#define mp make_pair
typedef pair<int, int> pii;
typedef priority_queue<int, vector<int>, greater<int> > small_heap;
typedef priority_queue<int> big_heap;
struct node {
    int w, s, v;
} wp[1009];
int n;
ll dp[20009], ans;

bool cmp(node a, node b) {
    return a.s + a.w < b.s + b.w;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d%d%d", &wp[i].w, &wp[i].s, &wp[i].v);
    }
    sort(wp + 1, wp + n + 1, cmp);
    for (int i = 1; i <= n; i++) {
        for (int j = 20000; j >= wp[i].w; j--) {
            if (wp[i].s + wp[i].w >= j)dp[j] = max(dp[j - wp[i].w] + 1ll * wp[i].v, dp[j]);
        }
    }
    ll ans = 0;
    for (int i = 1; i <= 20000; i++)ans = max(ans, dp[i]);
    printf("%lld\n", ans);
    return 0;
}

Measured memory_bytes: 384
from itertools import permutations
n = int(input())
P = tuple([int(i) for i in input().split()])
Q = tuple([int(i) for i in input().split()])

perms = sorted([p for p in permutations([i+1 for i in range(n)],n)])
print(abs(perms.index(P)-(perms.index(Q))))

Measured memory_bytes: 8308
//By Huseyn Hajiyev
#include <bits/stdc++.h>
#define FAST_READ ios_base::sync_with_stdio(false);
#define in freopen("input.txt", "r", stdin);
#define out freopen("output.txt", "w", stdout);
#define ll long long
#define VI vector<int>
#define VIL vector<long long>
#define debt(x,y)cout<<"#x = "<<(x)<<" and "<<"#y = "<<(y)<<endl;
#define deb(x)cout<<"#x = "<<(x)<<endl;
#define COUT(n, a) cout<< fixed << setprecision(a) << n<<endl
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define endl "\n"
#define arr(a,n) for(ll i=1;i<=n;i++) cout<<a[i]<<" "; cout << "\n";
#define vecc(a,n) for(ll i=0;i<n;i++) cout<<a[i]<<" "; cout << "\n";
#define huscout(n) cout<<n<<endl
#define husscanint(n) scanf("%d",&n)
#define setf(myset,it) for(auto  it=myset.end();it!=myset.begin();it--)
#define husscanll(n) scanf("%lld",&n)
#define husscandouble(n) scanf("%lf",&n)
#define husprintint(n)  printf("%d",n)
#define husprintll(n) printf("%lld",n)
#define MAXN 200010

using namespace std;

ll sorthus(ll i,ll j)
{
	return i>j;
}
//vector<ll>usedd;
const ll maxn = 1e6 + 1e3;
ll kolvo;
ll n;
ll cis;
set<ll,greater<ll> >lines;
map<ll,ll> usedd;
int main(){
FAST_READ;
cin>>n;

for(ll i=0;i<n;i++)
{
  cin>>cis;
  //cout<<cis<<endl;
  usedd[cis]++;
  //deb(usedd[cis]);
  lines.insert(cis);
}
/*
for(const auto &i:lines)
{
 cout<<i<<endl;
}
*/
//debt(*lines.begin(),*lines.end());
//deb(lines.size());
ll storonaone,storonatwo;
ll cnt=0;
storonaone=-MAXN;
storonatwo=-MAXN;
ll sig=1;
for(const auto &it:lines)
{
	//cout<<it<<" ";
	if(cnt<4)
  {
  kolvo=usedd[it];

  //deb(kolvo);
  if(kolvo>=4 && cnt==0){storonatwo=it;storonaone=storonatwo;cnt+=4;}
  else if(kolvo>=4 && cnt==2){storonatwo=it;cnt+=2;}
  else if(kolvo>=2 && kolvo<4 && cnt==0){storonaone=it;cnt+=2;}
  else if(kolvo>=2 && kolvo<4 && cnt==2 && storonaone!=it){storonatwo=it;cnt+=2;}
  }
  else {sig=0;break;}
	
}
//cout<<endl;
//debt(storonaone,storonatwo);
 
/*
sort(all(lines),sorthus);
//vecc(lines,lines.size());
ll sig=1;

for(ll i=0;i<n;i+=kolvo)
{
  //deb(lines[i]);
  if(cnt<4)
  {
  kolvo=count(all(lines),lines[i]);
  if(kolvo>=4 && cnt==0){storonatwo=lines[i];storonaone=storonatwo;cnt+=4;}
  else if(kolvo>=4 && cnt==2){storonatwo=lines[i];cnt+=2;}
  else if(kolvo>=2 && kolvo<4 && cnt==0){storonaone=lines[i];cnt+=2;}
  else if(kolvo>=2 && kolvo<4 && cnt==2 && storonaone!=lines[i]){storonatwo=lines[i];cnt+=2;}
  }
  else {sig=0;break;}
}
*/
//debt(storonatwo,storonaone);
if(storonaone>0 && storonatwo>0)cout<<storonatwo*storonaone<<endl;
else cout<<0<<endl;




return 0;
}

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


using namespace std;
typedef long long ll;

#define REP(i,n) for(ll i=0; i<ll(n); i++)
#define FOR(i,m,n) for(int i=int(m); i<int(n); i++)
#define ALL(obj) (obj).begin(),(obj).end()
template<typename T> using min_priority_queue = priority_queue<T, vector<T>, greater<T>>;

const int  INF = 1 << 29;
const ll INFL = 1LL << 60;
const ll mod = 1000000007;



int main() {

	ll h, n;
	cin >> h >> n;
	vector<pair<int, int>> a;
	REP(i, n) {
		int b, c;
		cin >> b >> c;
		a.push_back({ c,b });
	}

	vector<int> dp(10001, INF);
	dp[0] = 0;
	REP(i, h) {
		REP(j, n) {
			dp[min(i + a[j].second, h)] = min(dp[min(i + a[j].second, h)], dp[i] + a[j].first);
		}
	}


	cout << dp[h] << endl;

}

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

const int MA = 1e5 + 1;
vector<int> arr;
int dp[MA],n;

int main()
{   
    int k,x;//,mi,ma;
    cin>>n>>k;
    for(int i=0;i<n;i++) {
        cin>>x;
        arr.push_back(x);
    }
    //mi=arr[0];ma=arr[n-1];
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=k;i++){
        for(int move: arr){
            if(move>i) continue;
            if(dp[i-move]==0)
                dp[i]=1;
        }
    }
    if(dp[k])
        cout<<"First\n";
    else
        cout<<"Second\n";
    return 0;
}

Measured memory_bytes: 4000