akhauriyash/Code-Regression huggingface dataset:
#include<stdio.h>
#include<stdlib.h>

struct node{
  struct node *right;
  struct node *left;
  struct node *parent;
  int key;
};
typedef struct node * Node;
#define NIL NULL

Node root;

Node treeMinimum(Node x){
  while( x->left != NIL ) x = x->left;

  return x;
}

Node treeMaximum(Node x){
  while( x->right != NIL ) x = x->right;

  return x;
}

Node treeSearch(Node u, int k){
  while( u != NIL && k != u->key ){
    if( k < u->key ) u = u->left;
    else u = u->right;
  }

  return u;
}

Node treeSuccessor(Node x){
  if( x->right != NIL ) return treeMinimum(x->right);

  Node y = x->parent;

  while( y != NIL && x == y->right ){
    x = y;
    y = y->parent;
  }

  return y;
}

void treeDelete(Node z){
  Node y; // node to be deleted
  Node x; // child of y

  if( z->left == NIL || z->right == NIL ) y = z;
  else y = treeSuccessor(z);

  if( y->left != NIL ) x = y->left;
  else x = y->right;

  if( x != NIL ) x->parent = y->parent;

  if( y->parent == NIL ) root = x;
  else if( y == y->parent->left ) y ->parent->left = x;
  else y->parent->right = x;

  if( y != x ) z->key = y->key;

  free(y);
}

void insert(int k){
  Node y = NIL;
  Node x = root;
  Node z;

  z = malloc(sizeof(struct node));
  z->key = k;
  z->left = NIL;
  z->right = NIL;

  while( x != NIL ){
    y = x;
    if( z->key < x->key ){
      x = x->left;
    }
    else x= x->right;
  }

  z->parent = y;

  if( y == NIL ) root = z;
  else if ( z->key < y->key ) y->left = z;
  else y->right = z;
}

void inorder(Node u){

  if( u == NIL ) return;

  inorder(u->left);

  printf(" %d", u->key);

  inorder(u->right);

}

void preorder(Node u){

  if( u == NIL ) return;

  printf(" %d", u->key);

  preorder(u->left);
  preorder(u->right);

}

int main(){
  int n, i, x;
  char com[20];
  scanf("%d", &n);

  for ( i = 0; i < n; i++ ){
    scanf("%s", com);
    if ( com[0] == 'f' ){
      scanf("%d", &x);
      Node t = treeSearch(root, x);
      if ( t != NIL ) printf("yes\n");
      else printf("no\n");
    } else if ( com[0] == 'i' ){
      scanf("%d", &x);
      insert(x);
    } else if ( com[0] == 'p' ){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    } else if ( com[0] == 'd' ){
      scanf("%d", &x);
      treeDelete(treeSearch(root, x));
    }
  }

  return 0;
}

Measured memory_bytes: 19364
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _Book {
    char name[31];
    int page[1000];
    int pageno;
} Book;

Book book[1000];
int maxbook = 0;

int search(char *name) {
    int i;
    for (i = 0; i < maxbook; i++) {
	if (strcmp(book[i].name, name) == 0) {
	    return i;
	}
    }

    return -1;
}

int cmppage(const void *a, const void *b) {
    int *booka = (int *)a;
    int *bookb = (int *)b;

    if (*booka == *bookb)
	return 0;
    if (*booka < *bookb)
	return -1;
    if (*booka > *bookb)
	return 1;

    return 0;
}

void printbook() {
    int i, j;
    for (i = 0; i < maxbook; i++) {
	printf("%s\n", book[i].name);

	qsort(book[i].page, book[i].pageno, sizeof(int), cmppage);

	for (j = 0; j < book[i].pageno; j++) {
	    printf("%d", book[i].page[j]);
	    if (j != book[i].pageno - 1) {
		printf(" ");
	    }
	}
	printf("\n");
    }
}

int cmpbook(const void *a, const void *b) {
    Book *booka = (Book *)a;
    Book *bookb = (Book *)b;

    if (strcmp(booka->name, bookb->name) == 0)
	return 0;
    if (strcmp(booka->name, bookb->name) < 0)
	return -1;
    if (strcmp(booka->name, bookb->name) > 0)
	return 1;

    return 0;
}

int main(void) {
    int no;
    char tmpname[100];
    int tmppage;

    while (!feof(stdin)) {
	if (scanf("%s", tmpname) != 1)
	    break;
	scanf("%d", &tmppage);

	no = search(tmpname);
//	printf("%d ", tmppage);
	if (no == -1) {
	    int n = book[maxbook].pageno;
	    book[maxbook].page[n] = tmppage;
	    book[maxbook].pageno = 1;
	    strcpy(book[maxbook].name, tmpname);
	    maxbook++;
	} else {
	    int n = book[no].pageno;
	    book[no].page[n] = tmppage;
	    book[no].pageno++;
	    strcpy(book[no].name, tmpname);
	}
    }

    qsort(book, maxbook, sizeof(Book), cmpbook);

    printbook();

    return 0;
}

Measured memory_bytes: 0
H, W, N = map(int, input().split())
graph = [list(input()) for _ in range(H)]
from collections import deque


def bfs_gird(start, x_lim=H, y_lim=W):
    seen = {start}
    todo = deque()
    todo.append(start)
    dis = {start: 0}

    one_steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
    while todo:
        x, y, level = todo.popleft()
        for dx, dy in one_steps:
            nx, ny = x + dx, y + dy
            if not ((0 <= nx < x_lim) and (0 <= ny < y_lim)):
                continue
            if (nx, ny, level) in seen:
                continue
            elif graph[nx][ny] == "X":
                continue
            elif graph[nx][ny] == str(N) and level==N-1:
                return dis[(x, y, level)] + 1
            elif graph[nx][ny] == str(level+1):
                nxy = (nx, ny, level+1)
                dis[nxy] = dis[(x, y, level)] + 1
                if nxy not in seen:
                    todo.append(nxy)
                    seen.add(nxy)
            else:
                nxy = (nx, ny, level)
                dis[nxy] = dis[(x, y, level)] + 1
                if nxy not in seen:
                    todo.append(nxy)
                    seen.add(nxy)
        del dis[(x, y, level)]
def finds():
    for i in range(H):
        for j in range(W):
            if graph[i][j] == "S":
                return (i, j, 0)

ans = bfs_gird(finds())
print(ans)



Measured memory_bytes: 555760
#include<stdio.h>
#define N 100000
int A[N],n;
int bsearch(int);
int main(){
  int key,a,i,j,sum=0;
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%d",&A[i]);
  }
  scanf("%d",&a);
  for(j=0;j<a;j++){
    scanf("%d",&key);
    if(bsearch(key)){
      sum++;
    }
  }
  printf("%d\n",sum);
  return 0;
}
int bsearch(int k){
  int l=0,r,m;
  r=n;
  while(l<r){
    m=(r+l)/2;
    if(k==A[m]) return 1;
    if(k > A[m]){
      l = m+1;
    }
    else if(k < A[m]){
      r = m;
    }
  }
  return 0;
}

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

int N, A[404];
vector<vector<P>> memo;

P dp(int l, int r) {
    if(memo[l][r] != P(-1, -1)) return memo[l][r];
    if(l == r) return memo[l][r] = P(A[l], 0);
    ll ncost = 1e18;
    ll ns = 0;
    for(int i = l; i < r; ++i) {
        P ldp = dp(l, i);
        P rdp = dp(i + 1, r);
        ll s = ldp.first + rdp.first;
        ll cost = ldp.second + rdp.second;
        if(ncost > s + cost) {
            ncost = s + cost;
            ns = s;
        }
    }
    return memo[l][r] = P(ns, ncost);
}

int main() {
    cin >> N;
    rep(i, 0, N) cin >> A[i];
    memo.assign(N, vector<P>(N, P(-1, -1)));
    cout << dp(0, N - 1).second << endl;
    return 0;
}


Measured memory_bytes: 2816
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    string t;
    cin>>s>>t;
    int n=s.length();
    int m=t.length();
    int dp[n+1][m+1];
    for(int i=0;i<=n;i++)
    {
        for(int j=0;j<=m;j++)
        {
            if(i==0||j==0)
                dp[i][j]=0;
            else if(s[i-1]==t[j-1])
            {
                dp[i][j]=dp[i-1][j-1]+1;
            }
            else 
            {
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        }
    }
    int i=n,j=m;
    string ans(dp[n][m],'.');
    int c=1;
    int size=dp[n][m];
    while(i!=0&&j!=0)
    {
        if(dp[i][j]==dp[i-1][j-1]+1&&s[i-1]==t[j-1])
        {
            ans[size-c]=s[i-1];
           c++;
           i--;
           j--;
        }
        else if(dp[i][j]==dp[i-1][j])
        {
            i--;
        }
        else j--;
    }
    cout<<ans<<endl;
}

Measured memory_bytes: 35456
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>

using namespace std;

typedef long long ll;
typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<long long> vll, vLL;
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) for(int i=0;i<n;++i)
#define mod (ll)(1e9+7)
#define ALL(obj) (obj).begin(), (obj).end()
#define INF 1000000000 //1e9
#define LLINF 2000000000000000000LL //2e18

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n,m,x,y;
    cin >> n >> m >> x >> y;
    int xx[n];
    int yy[m];
    REP(i,n) cin >> xx[i];
    REP(i,m) cin >> yy[i];
    sort(xx,xx+n);
    sort(yy,yy+m);
    int xm = xx[n-1];
    int ym = yy[0];
    int f = false;
    for(int i=x+1;i<=y;i++){
        if(i>xm&&i<=ym){
            f = true;
            break;
        }
    }

    if(f){
        cout << "No War\n";
    }else{
        cout << "War\n";
    }
    return 0;
}


Measured memory_bytes: 256
#include<set>
#include<map>
#include<ctime>
#include<queue>
#include<cmath>
#include<cstdio>
#include<vector>
#include<climits>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
int read(){
    int f=1,x=0;char s=getchar();   
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}  
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    return x*f;
}
#define eps 1e-8
#define MAXN 100
#define INF 0x3f3f3f3f
#define Mod int(1e9+7)
int x[MAXN+5],y[MAXN+5],h[MAXN+5];
int main(){
	int n=read();
	for(int i=1;i<=n;i++)
		x[i]=read(),y[i]=read(),h[i]=read();
	for(int H=1;H<=200;H++)
	for(int Cx=0;Cx<=MAXN;Cx++)
		for(int Cy=0;Cy<=MAXN;Cy++){
			int f=0;
			for(int i=1;i<=n;i++)
				if(max(H-abs(Cx-x[i])-abs(Cy-y[i]),0)!=h[i]){
					f=1;
					break;
				}
			if(!f){
				printf("%d %d %d\n",Cx,Cy,H);
				return 0;
			}
		}
	for(int Cx=0;Cx<=MAXN;Cx++)
		for(int Cy=0;Cy<=MAXN;Cy++){
			int H=h[1]+abs(Cx-x[1])+abs(Cy-y[1]),f=0;
			for(int i=2;i<=n;i++)
				if(h[i]+abs(Cx-x[i])+abs(Cy-y[i])!=H){
					f=1;
					break;
				}
			if(!f){
				printf("%d %d %d\n",Cx,Cy,H);
				return 0;
			}
		}
	return 0;
}

Measured memory_bytes: 256
#include <stdio.h>

int main(void){
    int a,b;
    scanf("%d%d",&a,&b);
    if(0 < a < 100 && 2 < b < 1000 && b%2 == 0){
        if(13 <= a){
            printf("%d\n",b);
        }else if(6 <= a && a <= 12){
            printf("%d\n",b/2);
        }else if(a <= 5){
            printf("%d\n",0);
        }
    }
}

Measured memory_bytes: 128
# coding: utf-8
A = int(input())
B = int(input())
C = int(input())
X = int(input()) // 50
ans = 0
for i in range(A + 1):
    for j in range(B + 1):
        for k in range(C + 1):
            if 10 * i + 2 * j + k == X:
                ans += 1
print(ans)

Measured memory_bytes: 3060
#include <bits/stdc++.h>
#include<math.h>
#include<climits>
#define ll long long
#define VAL 100
using namespace std;
int main()
{
    int i,j,t;
    string str;
    cin>>str;
    int count=1;
    int maxcount=0;
    bool flag=false;
    if(str[0]=='R')
    {
        flag=true;
    }
    for(int i=1;i<str.length();i++)
    {
        if(str[i]=='R')
        {
            flag=true;
        }
        if((str.at(i)==str.at(i-1))&&(str[i]=='R'))
        {
                count++;
                maxcount=max(count,maxcount);
        }
        else
        {
            count=1;
        }
    }
    if(maxcount==0)
    {
        if(flag==true)
        {
            cout<<1<<endl;
        }
        else
        cout<<maxcount<<endl;
    }
    else
    {
        cout<<maxcount<<endl;
    }

    return 0;
}



Measured memory_bytes: 3616
#import numpy as np
import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial#, gcd
from bisect import bisect_left, bisect_right #bisect_left(list, value)
sys.setrecursionlimit(10**7)
enu = enumerate
MOD = 10**9+7
def input(): return sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep='\n')

N = int(input())
A = list(map(int, input().split()))
A.sort()
C = Counter(A)
S = set(A)

maxA = A[-1]
chk = [0] * (maxA+1)
for s in S:
    for i in range(s, maxA+1, s):
        chk[i] += 1

res = [s for s in S if chk[s] == 1 and C[s] == 1]
# print(res)
print(len(res))

Measured memory_bytes: 164772
import math
from itertools import accumulate

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

fromleft = list(accumulate(a, math.gcd))
a.reverse()
fromright = list(accumulate(a, math.gcd))
fromright.reverse()
a.reverse()

gcd = []

gcd.append(fromright[1])
for i in range(1, n-1):
    gcd.append(math.gcd(fromleft[i-1], fromright[i+1]))

gcd.append(fromleft[n-2])

if n == 2:
    print(max(a[1], a[0]))
else:
    print(max(gcd))


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

int main()
{
    int n,a;
    cin >> n >> a;
    cout << n*n-a << endl;
    return 0;
}

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

#define For(i,l,r) for(int i=l;i<=r;i++)
#define ForR(i,l,r) for(int i=l;i>=r;i--)
#define ll long long
int main(){
//	freopen(".inp","r",stdin);
// 	freopen(".out","w",stdout);
	ll n;
	bool ktra=true;
	cin>>n;
	ll a[n+10];
	For(i,1,n){
		cin>>a[i];
		
	}
	sort(a+1,a+n+1);
	For(i,1,n-1)
		if(a[i]==a[i+1]){cout<<"NO";return 0;}
		cout<<"YES";
		}
		

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

using namespace std;

signed main(){
	string s;
	cin >> s;
	int cntg = 0, cntp = 0, sc = 0;
	for(int i = 0; i < s.length(); i++){
		if(s[i] == 'g'){
			if(cntp < cntg){
				cntp++;
				sc++;
			}
			else
				cntg++;
		}
		else{
			if(cntp < cntg)
				cntp++;
			else{
				cntg++;
				sc--;
			}
		}
	}
	cout << sc;
}

Measured memory_bytes: 512
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
using namespace std;
typedef	long long ll;
typedef unsigned long long ull;
#define all(v) ((v).begin()),((v).end())
#define PI(n) ((double)acos(n))
#define clr0(n) (memset(n,0,sizeof n))
#define clr1(n) (memset(n,-1,sizeof n))
int dx8[8] = { 1, -1, 0, 0, 1, 1, -1, -1 };
int dy8[8] = { 0, 0, 1, -1, 1, -1, 1, -1 };
void file()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
#else
	// online submission
#endif
}
void fast()
{
	std::ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
}
int main()
{
	fast();
	int n;
	cin >> n;
	cout << "ABC" << n << endl;
}

Measured memory_bytes: 256
from collections import Counter,defaultdict,deque
import sys
import bisect
import math
import itertools
import string
import queue
import copy
# import numpy as np
# import scipy
from itertools import permutations, combinations
from heapq import heappop, heappush
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
 
def inp(): # n=1
    return int(input())
def inpm(): # x=1,y=2
    return map(int,input().split())
def inpl(): # a=[1,2,3,4,5,...,n]
    return list(map(int, input().split()))
def inpls(): # a=['1','2','3',...,'n']
    return list(input().split())
def inplm(n): # x=[] 複数行
    return list(int(input()) for _ in range(n))
def inpll(n): # [[1,1,1,1],[2,2,2,2],[3,3,3,3]]
    return [list(map(int, input().split())) for _ in range(n)]
 
 
def main():
    h,w = inpm()
    maze = []
    for _ in range(h):
        s = list(input())
        maze.append(s)
    ans = 0
    dx=[1,0,-1,0]
    dy=[0,1,0,-1]
    for sx in range(h):
        for sy in range(w):
            if maze[sx][sy] == '#':
                continue
            else:
                d = [[-1 for _ in range(w)] for _ in range(h)]
                que = []
                d[sx][sy] = 0
                que.append((sx,sy))
                M = 0
                while que:
                    [qx,qy]=que[0]
                    que.pop(0)
                    for i in range(4):
                        nx=qx+dx[i]
                        ny=qy+dy[i]
                        if nx>=0 and h>nx and ny>=0 and w>ny and maze[nx][ny]=="." and d[nx][ny]==-1:
                            d[nx][ny]=d[qx][qy]+1
                            if d[qx][qy]+1>M:
                                M= d[qx][qy]+1
                            que.append((nx,ny))
                ans = max(ans,M)
    print(ans)
 
 
if __name__ == "__main__":
    main()

Measured memory_bytes: 46424
n,m,X,Y = (int(i) for i in input().split())
x = [int(i) for i in input().split()]
y = [int(i) for i in input().split()]

z = min(y)
if z <= max(x):
    print("War")
else:
    if X < z <= Y:
        print("No War")
    else:
        print("War")

Measured memory_bytes: 38384
dict = {}
n = int(input())
for _ in range(n):
    key, value = map(str, raw_input().split())
    if key in dict:
        dict[key] += int(value)
    else:
        dict[key] = int(value)

for k in sorted(sorted(dict.keys()), key=len):
    print k, dict[k]

Measured memory_bytes: 4516
import java.util.Scanner;

//Ring
public class Main{

	void run(){
		Scanner sc = new Scanner(System.in);
		String s = sc.next();
		int n = sc.nextInt();
		int c = 0;
		while(n--!=0){
			String t = sc.next();
			t = t+t;
			if(t.contains(s))c++;
		}
		System.out.println(c);
	}
	
	public static void main(String[] args) {
		new Main().run();
	}
}

Measured memory_bytes: 12000
#include<stdio.h>
int main(void)
{
	int a,b,c,d,e,t,h,g;
	scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
	if(a<0){
		t=-a*c;
		h=b*e;
		g=t+h+d;
	}
	else if(a==0){
		h=b*e;
		g=h+d;
	}
	else if(a>0){
		h=b-a;
		g=h*e;
	}
	printf("%d\n",g);
	return 0;
}


Measured memory_bytes: 2104
import java.io.*;
import java.util.*;
import java.math.*;
import java.util.concurrent.*;

class Main
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	static long mod=(long)(1e9+7);
	static long[] fact,inv_fact;
	static int maxn=(int)(1e5+5);
	
	static long pow(long a,long b)
	{
		long x=1,y=a;
		
		while(b>0)
		{
			if(b%2==1)
			{
				x=(x*y)%mod;
			}
			
			y=(y*y)%mod;b=b/2;
		}
		
		return x;
	}
	
	static void build()
	{
		fact=new long[maxn];inv_fact=new long[maxn];fact[0]=1;
		
		for(int i=1;i<maxn;i++)
		{
			fact[i]=(fact[i-1]*i)%mod;
		}
		
		inv_fact[maxn-1]=pow(fact[maxn-1],mod-2);
		
		for(int i=maxn-2;i>=0;i--)
		{
			inv_fact[i]=(inv_fact[i+1]*(i+1))%mod;
		}
	}
	
	static long C(int n,int r)
	{
		if(n<r || Math.min(n,r)<0) return 0;
		
		long val1=fact[n],val2=inv_fact[r],val3=inv_fact[n-r];
		
		long val4=(val2*val3)%mod;
		
		return (val1*val4)%mod;
	}
	
    public static void main(String args[]) throws Exception
    {
		build();int n=sc.nextInt(),pos1=-1,pos2=-1;int[] a=new int[n+2],pos=new int[n+1];
		
		for(int i=1;i<=n+1;i++)
		{
			a[i]=sc.nextInt();
			
			if(pos[a[i]]!=0)
			{
				pos1=pos[a[i]];
				
				pos2=i;
			}
			
			pos[a[i]]=i;
		}
		
		long[] f=new long[n+2];f[1]=n;
		
		for(int i=2;i<=n+1;i++)
		{
			f[i]=C(n+1,i);
		}
		
		for(int i=2;i<=n+1;i++)
		{
			int sum=pos1-1+(n+1-pos2);
			
			long now=C(sum,i-1);
			
		//	out.println(sum+" "+i);
			
			f[i]=(f[i]-now+mod)%mod;
		}
		
		for(int i=1;i<=n+1;i++)
		{
			out.println(f[i]);
		}
		
		out.close();
    }
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }
	
    public String nextToken() throws Exception {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }
	
	public String next() throws Exception {
		return nextToken().toString();
	}
	
    public int nextInt() throws Exception {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws Exception {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }
}

Measured memory_bytes: 43340
#最大公約数
def gcd(a,b):
    while b!=0:
        a,b = b,a%b
    return a
 #最小公倍数
def lcm(a,b):
    return a*b // gcd(a,b)

def calc_num(n, C, D):
    """
    0~Nまでで、C or Dで割り切れない数の個数
    """
    div_C = n//C
    div_D = n//D
    div_CD = n//(lcm(C, D))
    return n-div_C-div_D+div_CD


def solve():
    A, B, C, D = map(int, input().split())
    return calc_num(B, C, D)-calc_num(A-1, C, D)

print(solve())

Measured memory_bytes: 3064
package main

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

func main() {

	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	_, _ = fmt.Fscan(reader, &n)
	edges := make([][]int, n)
	a := make([]int, n - 1)
	b := make([]int, n - 1)
	for i := 0; i < n - 1; i++ {
		_, _ = fmt.Fscan(reader, &a[i], &b[i])
		a[i]--
		b[i]--
		edges[a[i]] = append(edges[a[i]], i)
		edges[b[i]] = append(edges[b[i]], i)
	}
	col := make([]int, n - 1)
	for i := 0; i < n - 1; i++ {
		col[i] = 0
	}
	var f func(x int, pre int)
	f = func(x int, pre int) {
		nex := 0
		for _, i := range edges[x] {
			y := a[i]
			if x == y {
				y = b[i]
			}
			if col[i] == 0 {
				nex++
				if pre == nex {
					nex++
				}
				col[i] = nex
				f(y, col[i])
			}
		}
	}
	f(0, -1)
	k := 1
	for _, c := range col {
		if k < c {
			k = c
		}
	}
	_, _ = fmt.Fprintln(writer, k)
	for _, c := range col {
		_, _ = fmt.Fprintln(writer, c)
	}
}



Measured memory_bytes: 19828
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef vector<ll> vl;
typedef vector<string> vs;
typedef vector<char> vc;
typedef queue<ll> ql;
typedef deque<ll> dql;
typedef priority_queue<ll, vl/*, greater<ll>*/> pql; //降順(/*昇順*/)
typedef set<ll> sl;
typedef pair<ll, ll> pl;
typedef vector<vl> vvl;
typedef vector<pl> vpl;
#define rep(i, n) for(ll i = 0; i < ll(n); ++i)
#define rep2(i, n) for(ll i = 1; i <= ll(n); ++i)
//#define rep(i, k, n) for(ll i = k-1; i < ll(n); ++i)
//#define rep2(i, k, n) for(ll i = k; i <= ll(n); ++i)
#define all(v) (v).begin(), (v).end()
bool chmin(ll &a, ll b) {if(b < a) {a = b; return 1;} return 0;}
bool chmax(ll &a, ll b) {if(b > a) {a = b; return 1;} return 0;}
const ll INF = 1LL << 60;
const ll MOD = 1e9 + 7;
//const ll MOD = 998244353;
const ll MAX = 1e9;
const char newl = '\n';

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

  ll n;
  cin >> n;
  
  ll m=0;
  while(m*(m+1)<2*n) m++;
  vl ans;
  while(m) {
    if(m<=n) {n -= m; ans.push_back(m);}
    m--;
  }
  for(ll i: ans) cout << i << newl;
}

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

const int MAX_L = 25000;

int n, opt_len = 0;
int opt[MAX_L];

void move(int cur, vector<int>&p, vector<int>&par) {
	opt[opt_len++] = cur;
	int v = cur, tmp = p[0];
	while (true) {
		swap(p[v], tmp);
		if (v == 0)
			break;
		v = par[v];
	}
}

int main() {
	ios::sync_with_stdio(false);
	
	cin >> n;
	vector<int> p(n), par(n, 0), deg(n, 0);
	vector<vector<int> > edges(n);
	
	for (int i = 1; i < n; ++i) {
		cin >> par[i];
		++deg[par[i]];
		edges[par[i]].push_back(i);
	}
	
	for (int i = 0; i < n; ++i) {
		cin >> p[i];
	}
	
	vector<bool> same(n, 0);
	while (!same[0]) {
		vector<int> in_path(n, -1), in_path_id(n, -1);
		vector<vector<pair<int, int> > > paths;
		
		for (int i = n - 1; i >= 0; --i) {
			if (!same[i] && deg[i] == 0) {
				vector<pair<int, int> > path;
				int v = i;
				while (deg[v] <= 1) {
					in_path[v] = paths.size();
					path.push_back(make_pair(v, -1));
					if (v == 0)
						break;
					v = par[v];
				}
				
				reverse(path.begin(), path.end());
				
				for (int j = 0; j < path.size(); ++j) {
					in_path_id[path[j].first] = j;
				}
				paths.push_back(path);
			}
		}
		
		int cur = n - 1;
		while (true) {
			int v = p[0];
			if (in_path[v] != -1) {
				int pos = in_path[v], x = (int)paths[in_path[v]].size() - 1;
				while (paths[pos][x].second > v) {
					--x;
				}
				
				for (int i = 1; i <= x; ++i) {
					paths[pos][i - 1].second = paths[pos][i].second;
				}
				paths[pos][x].second = v;
				move(paths[pos][x].first, p, par);
			}
			
			while (cur >= 0) {
				if (same[cur])
					--cur;
				else {
					if (in_path[cur] != -1 && paths[in_path[cur]][in_path_id[cur]].second != -1)
						--cur;
					else
						break;
				}
			}
			
			if (cur < 0)
				break;
			if (in_path[v] == -1) {
				move(cur, p, par);
				--cur;
			}
		}
		
		for (int i = 0; i < n; ++i) {
			if (in_path[i] != -1) {
				same[i] = true;
				--deg[par[i]];
			}
		}
	}
	
	cout << opt_len << "\n";
	for (int i = 0; i < opt_len; ++i) {
		cout << opt[i] << "\n";
	}
}

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

//N以下の素数列挙。O(N log log N)
int N = 100000;
vector<int> primes;
vector<bool> is_prime(N + 1, true);
void init() {
        is_prime[0] = is_prime[1] = false;
        for (int i = 2; i <= N; i ++) {
                if (is_prime[i]) {
                        primes.push_back(i);
                        for (int j = i + i; j <= N; j += i) is_prime[j] = false;
                }
        }
}

long long gcd(long long a, long long b) {
        while (b) {
                a %= b;
                swap(a, b);
        }
        return a;
}

long long lcm(long long a, long long b) {
        return a / gcd(a, b) * b;
}

int main() {
        init();
        const int n = 500;
        vector<vector<long long>> s(n, vector<long long> (n));
        rep(i, n) {
                rep(j, n) {
                        if ((i + j) & 1) {
                                s[i][j] = primes[(j - i - 1) / 2 + n / 2] * primes[(j + i - 1) / 2 + n];
                        }
                }
        }
        /*
                rep(i, n) {
                        rep(j, n) cerr << s[i][j] << ' '; cerr << endl;
                }
        */
        rep(i, n) {
                rep(j, n) {
                        if ((i + j) % 2 == 0) {
                                long long g = 1;
                                if (i > 0) g = lcm(g, s[i - 1][j]);
                                if (j > 0) g = lcm(g, s[i][j - 1]);
                                if (i < n - 1) g = lcm(g, s[i + 1][j]);
                                if (j < n - 1) g = lcm(g, s[i][j + 1]);
                                s[i][j] = g + 1;
                        }
                }
        }
        int p;
        scanf("%d", &p);
        rep(i, p) {
                rep(j, p) {
                        printf("%lld%c", s[i][j], (j == p - 1 ? '\n' : ' '));
                }
        }
        return 0;
}


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

int main() {
	int H = -1, W = -1;
	vector<pair<int,int> > inputs;

	while(true) {
		cin >> H >> W;
		if(H == 0 && W == 0) break;
		else inputs.push_back(pair<int,int>(H,W));
	}

	vector<pair<int,int> >::iterator it = inputs.begin();
	while(it != inputs.end()) {
		//	cout << (*it).first << ", " << (*it).second << endl;
		for(int i = 0; i < (*it).first; ++i) {
			for(int j = 0; j < (*it).second; ++j) {
				if(j%2==i%2) cout << "#";
				else cout << ".";
			}
			cout << endl;
		}
		cout << endl;
		++it;
	}
	return 0;
}

Measured memory_bytes: 1192
import sys
input = sys.stdin.readline
from collections import defaultdict
def main():
    N = int( input())
    S = [ input().strip() for _ in range(N)]
    d = defaultdict( int)
    for s in S:
        d[s] += 1
    m = 0
    for _, v in d.items():
        if v > m:
            m = v
    ANS = []
    for w, v in d.items():
        if v == m:
            ANS.append(w)
    ANS.sort()
    print("\n".join(ANS))
if __name__ == '__main__':
    main()


Measured memory_bytes: 35948
#include <bits/stdc++.h>
using namespace std;
#pragma GCC target("avx")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
typedef long long ll;
typedef pair<ll,ll> prl;
typedef vector<ll> vcl;
typedef map<ll,ll> mapl;
typedef unordered_map<ll,ll> umap;
#define pb push_back
#define all(v) v.begin(), v.end()
#define rep(i,a,b) for(ll i=a;i<=b;i++)
#define repi(i,a,b) for(int i=a;i<=b;i++)
#define repr(i,a,b) for(ll i=a;i>=b;i--)
#define reps(i,v) for(ll i=0;i<v.size();i++)
template<typename T> void chmin(T &a, const T &b) { a = min(a, b); }
template<typename T> void chmax(T &a, const T &b) { a = max(a, b); }
const ll mod = 998244353;

int main() {
    // your code goes here
    ll n,a[100005],ans=1;
    cin >> n;
    rep(i,1,n){
    	cin >> a[i];
    	if(a[i]==0){
    		cout << 0 << endl;
    		return 0;
    	}
    }
    rep(i,1,n){
    	if(ans!=0&&(1000000000000000000-1000000000000000000%ans)/ans<a[i]) {
    		cout << -1 << endl;
    		return 0;
    	}
    	ans*=a[i];
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 4396
import sys
## io ##
def IS(): return sys.stdin.readline().rstrip()
def II(): return int(IS())
def MII(): return list(map(int, IS().split()))
def MIIZ(): return list(map(lambda x: x-1, MII()))
## dp ##
def DD2(d1,d2,init=0): return [[init]*d2 for _ in range(d1)]
def DD3(d1,d2,d3,init=0): return [DD2(d2,d3,init) for _ in range(d1)]
## math ##
def to_bin(x: int) -> str: return format(x, 'b') # rev => int(res, 2)
def to_oct(x: int) -> str: return format(x, 'o') # rev => int(res, 8)
def to_hex(x: int) -> str: return format(x, 'x') # rev => int(res, 16)
MOD=10**9+7
def divc(x,y) -> int: return -(-x//y)
def divf(x,y) -> int: return x//y
def gcd(x,y):
    while y: x,y = y,x%y
    return x
def lcm(x,y): return x*y//gcd(x,y)
def enumerate_divs(n):
    """Return a tuple list of divisor of n"""
    return [(i,n//i) for i in range(1,int(n**0.5)+1) if n%i==0]
def get_primes(MAX_NUM=10**3):
    """Return a list of prime numbers n or less"""
    is_prime = [True]*(MAX_NUM+1)
    is_prime[0] = is_prime[1] = False
    for i in range(2, int(MAX_NUM**0.5)+1):
        if not is_prime[i]: continue
        for j in range(i*2, MAX_NUM+1, i):
            is_prime[j] = False
    return [i for i in range(MAX_NUM+1) if is_prime[i]]
## libs ##
from itertools import accumulate as acc
from collections import deque, Counter
from heapq import heapify, heappop, heappush
from bisect import bisect_left

#======================================================#

def main():
    n, x = MII()
    aa = MII()
    aa.sort()
    cnt = 0
    if x > sum(aa):
        cnt -= 1
    for a in aa:
        if x >= a:
            x -= a
            cnt += 1
    print(cnt)

if __name__ == '__main__':
    main()

Measured memory_bytes: 3316
#include <bits/stdc++.h>
#define ll long long
#define db long double
#define x first
#define y second
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define all(a) a.begin(), a.end()

using namespace std;

struct st {
	char c;
	int a, b, cc;
	st() {}
	st(char c, int a, int b, int cc): c(c), a(a), b(b), cc(cc) {}
};
vector<st> ans;
int last = 3;
int pos_1 = 200000 - 1;
const int STEP = 30; // 30

void create_2(int from, int step, int to) {
	if (step == 0) {
		ans.pb({'+', from, to, to});
		return;
	}
	int la = from;
	for (int i = 0; i < step; ++i) {
		int now = last++;
		ans.pb({'+', la, la, now});
		la = now;
	}
	ans.pb({'+', la, to, to});
}

int create_a(int v) {
	int new_a = last++;

	ans.pb({'+', 0, pos_1, new_a});

	int base = last++;
	int now = last++;
	vector<pair<int, int> > kek;
	kek.pb({now, 0});
	ans.pb({'+', now, v, now});
	for (int v = 1; v < STEP; ++v) {
		int new_now = last++;
		ans.pb({'+', now, now, new_now});
		now = new_now;
		kek.pb({now, v});
	}
	reverse(all(kek));
	for (auto [w1, w2] : kek) {
		int now = last++;
		ans.pb({'+', base, w1, now});
		int pp = last++;
		ans.pb({'<', now, new_a, pp});
		
		int kkk = last++;
		ans.pb({'+', v, pp, kkk});
		ans.pb({'<', pos_1, kkk, pp});
		create_2(pp, w2, base);
	}
	return base;
}


int mult(int pos, int step) {
	if (step == 0) {
		return pos;
	}
	int la = pos;
	for (int v = 0; v < step; ++v) {
		int now = last++;
		ans.pb({'+', la, la, now});
		la = now;
	}
	return la;
}


void check() {
	vector<ll> a(200000, 0);
	a[0] = 5;
	a[1] = 5;
	for (auto c : ans) {
		assert(c.a < 2e5);
		assert(c.b < 2e5);
		assert(c.c < 2e5);
		if (c.c == '+') {
			a[c.cc] = a[c.a] + a[c.b];
		} else if (c.c == '<') {
			a[c.cc] = a[c.a] < a[c.b];
		} else assert(0);
 	}

//	for (int i = 0; i < 22; ++i) cout << i << ' ' << a[i] << endl;
//		cout << endl;

	cout << "===" << a[2] << endl;
}


void go() {
	int new_b = last++;

	ans.pb({'+', 1, pos_1, new_b});

	int base = last++;
	int now = last++;
	vector<pair<int, int> > kek;
	kek.pb({now, 0});
	ans.pb({'+', now, pos_1, now});
	for (int v = 1; v < STEP; ++v) {
		int new_now = last++;
		ans.pb({'+', now, now, new_now});
		now = new_now;
		kek.pb({now, v});
	}
	reverse(all(kek));
	for (auto [w1, w2] : kek) {
	//	ans.pb({'e', 1111,1111, 1111});
		int now = last++;
		ans.pb({'+', base, w1, now});
		int pp = last++;
		ans.pb({'<', now, new_b, pp});
		int new_a = create_a(pp);
		int step_a = mult(new_a, w2);
	//	cout << "aaa" << step_a << endl;
		ans.pb({'+', step_a, 2, 2});
		create_2(pp, w2, base);
	}
}


int main(){
#ifdef LOCAL
	freopen("E_input.txt", "r", stdin);
	//freopen("E_output.txt", "w", stdout);
#endif
	ios_base::sync_with_stdio(0);
	cin.tie(0);


	ans.pb({'+', 0, 1, 199998});
	ans.pb({'<', 199999, 199998, 199999});

	go();

//	check();
	
	cout << ans.size() << endl;
	for (auto c : ans) {
		cout << c.c << ' ' << c.a << ' ' << c.b << ' ' << c.cc << "\n";
	}
}


Measured memory_bytes: 3764
#include <stdio.h>
#include <limits.h>
#include <math.h>
#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>

#define VARIABLE(x) cerr << #x << "=" << x << endl
#define BINARY(x) static_cast<bitset<16> >(x);
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define if_range(x, y, w, h) if (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))

const int INF = 100000000;
typedef double D;
const double EPS = 1e-8;
const double PI = 3.14159;
int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1};
using namespace std;
typedef pair<int, int> P;

/** Problem2149 : Luck Manipulator **/
int main()
{
	int N, A, B, C, X;
	while (cin>>N>>A>>B>>C>>X, N||A||B||C||X) {
		int ans = -1;
		vector<int> list(N);
		rep(i, N) cin>>list[i];
		
		int idx=0;
		
		rep(i, 10001) {
			int XX = X;
			
			if (i>0)
				 XX = (A*X+B)%C;
			
			if (XX == list[idx]) idx++;
			if (idx == N) {
				ans = i;
				break;
			}
			X = XX;
		}
		
		cout << ans << endl;
	}
}

Measured memory_bytes: 1196
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main (int argc, char const *argv[])
{
    int64_t A, P;
    int64_t ans = 0;

    scanf("%"PRId64"%"PRId64, &A, &P);

    ans = (A * 3 + P) / 2;

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


Measured memory_bytes: 128
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
int main(){
int N; 
string S;
cin >> N >> S; 
int A[110] = {}; 
int mini = 0; 
for(int i = 1; i <= N; i++){
if(S.at(i-1) == '('){
A[i] = A[i-1] + 1; 
}
else if(S.at(i-1) == ')'){
A[i] = A[i-1] - 1; 
}
mini = min(mini, A[i]); 
}
int B[110] = {}; 
int mini2 = 0; 
for(int i = N; i >= 1; i--){
if(S.at(i-1) == '('){
B[i] = B[i+1] - 1; 
}
else if(S.at(i-1) == ')'){
B[i] = B[i+1] + 1; 
}
mini2 = min(mini2, B[i]); 
}
string T = {}, U = {}; 
if(mini < 0){
for(int i = 0; i < abs(mini); i++){
T = T + '('; 
}
}
S = T + S; 
if(mini2 < 0){
for(int i = 0; i < abs(mini2); i++){
U = U + ')'; 
}
}
S = S + U; 
cout << S << endl; 
}

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

#define d(x) cerr << #x ":" << x << endl;
#define dd(x, y) cerr << "(" #x "," #y "):(" << x << "," << y << ")" << endl
#define rep(i, n) for (int i = (int)(0); i < (int)(n); i++)
#define all(v) v.begin(), v.end()
#define dump(v)                  \
    cerr << #v ":[ ";            \
    for (auto macro_vi : v) {    \
        cerr << macro_vi << " "; \
    }                            \
    cerr << "]" << endl;
#define ddump(v)                           \
    cerr << #v ":" << endl;                \
    for (auto macro_row : v) {             \
        cerr << "[";                       \
        for (auto macro__vi : macro_row) { \
            cerr << macro__vi << " ";      \
        }                                  \
        cerr << "]" << endl;               \
    }
using lint       = long long;
const int INF    = 1e9;
const lint LINF  = 1e18;
const double EPS = 1e-10;

int main() {
    lint N;
    cin >> N;

    const lint M = 1001000;
    vector<lint> min_factor(M, 1);
    for (int p = 2; p <= M; p++) {
        if (min_factor[p] != 1) continue;
        for (int pk = p; pk <= M; pk += p) {
            if (min_factor[pk] == 1) min_factor[pk] = p;
        }
    }

    lint ans = 0;

    for (lint c = 1; c < N; c++) {
        lint T = N - c;

        if (T == 1) {
            ans += 1;
        } else {

            map<int, int> cnt{};
            while (T != 1) {
                cnt[min_factor[T]]++;
                T /= min_factor[T];
            }

            lint tmp = 1;
            for (auto p : cnt) {
                int prime = p.first;
                int num   = p.second;
                tmp *= (num + 1);
            }
            ans += tmp;
        }
    }

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

Measured memory_bytes: 11132
#coding:utf-8
import sys

input_nums = [int(x) for x in sys.stdin.readline().split()]

if len(input_nums) > 2 :
	sys.exit("illegal input")
    
if (sum(input_nums)) > 16:
  sys.exit("illegal input")
  
if (min(input_nums)) < 1:
  sys.exit("illegal input")

max_num = max(input_nums)
if max_num > 16:
  sys.exit("illegal input")
elif max_num > 8:
  print(":(")
else :
  print('Yay!')

Measured memory_bytes: 3064
#include<stdio.h>
#include<algorithm>
#include<functional>
#include<cmath>
using namespace std;
int main()
{
	int N, X, L[110], D = 0;
	scanf("%d%d", &N, &X);
	for (int i = 0; i < N; i++) {
		scanf("%d", &L[i]);
	}
	int count = 1;
	for (int i = 0; i < N; i++) {
		D += L[i];
		if (D > X) {
			printf("%d", count);
			return 0;
		}
		count++;
	}
	printf("%d", count);
	return 0;
}

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

int main(){
	string s;
	cin>>s;
	if(s=="SSS") cout<<0<<endl;
	else if(s=="RRR") cout<<3<<endl;
	else if(s=="RRS"||s=="SRR") cout<<2<<endl;
	else cout<<1<<endl;
	return 0;
} 

Measured memory_bytes: 3624
#include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a; i < (b); i++)
#define rrep(i, a, b) for (int i = a; i >= (b); i--)
#define all(x) (x).begin(), (x).end()
using namespace std;
using ll = long long;
using P = pair<int, int>;
template <class T>
inline bool chmin(T& a, T b) {
   if (a > b) {
      a = b;
      return true;
   }
   return false;
}
template <class T>
inline bool chmax(T& a, T b) {
   if (a < b) {
      a = b;
      return true;
   }
   return false;
}
const int INF = 2e9;
const int MOD = 1e9 + 7;

int main() {
   while (true) {
      int n, x;
      cin >> n >> x;
      if (n == 0 && x == 0) break;
      int ans = 0;
      rep(i, 1, n + 1) rep(j, i + 1, n + 1) rep(k, j + 1, n + 1) {
         if (i + j + k == x) ans++;
      }
      cout << ans << endl;
   }
   return 0;
}


Measured memory_bytes: 3112
use proconio::input;

fn main() {
	const MOD: u64 = 1_000_000_007;

	input!(n: usize, m: usize, a: [usize; m]);

	let mut broken = vec![false; n+1];
	for i in a { broken[i] = true };

	let mut dp = vec![1];
	dp.push(if broken[1] { 0 } else { dp[0] });
	for i in 1..n {
		dp.push(if broken[i+1] { 0 } else { (dp[i] + dp[i-1]) % MOD });
	}

	println!("{}", dp[n]);
}

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

res = 0


def digitSum(n):
    s = str(n)
    array = list(map(int, s))
    return sum(array)


for nn in range(0,n+1):
    if a<= digitSum(nn) <= b:
        res += nn
print (res)


Measured memory_bytes: 3060
#include <cstdio>
#include <algorithm>
#include <vector>
#include <set>
#include <cstdlib>
#include <utility>
#include <cmath>
#include <queue>
#include <stack>
#include <cstring>

using namespace std;

#define ll long long

#ifndef ONLINE_JUDGE
#define debug(format, ...) fprintf(stderr, \
    "%s:%d: " format "\n", __func__, __LINE__,##__VA_ARGS__)
#else
#define debug(format, ...)
#define NDEBUG
#endif

int n;
int a[200005];
int res[200005];

ll ans = 0;

int fix(int A)
{
    if (A <= 0) A += n;
    if (A > n) A -= n;
    return A;
}

bool ishigh(int pos)
{
    return a[pos] > a[fix(pos-1)] + a[fix(pos+1)];
}

int main()
{
    scanf("%d", &n);
    queue<int> que;
    for (int i = 1; i <= n; i++) scanf("%d", res + i);
    for (int i = 1; i <= n; i++) scanf("%d", a + i);
    for (int i = 1; i <= n; i++) {
        if (ishigh(i)) que.push(i);
    }
    while (!que.empty()) {
        int pos = que.front(); que.pop();
        int around = a[fix(pos-1)] + a[fix(pos+1)];
        //debug("%d", pos);
        if (res[pos] > (a[pos] % around)) {
            if (a[pos] < res[pos] || (a[pos] - res[pos]) % around || a[fix(pos+1)] != res[fix(pos+1)]
                || a[fix(pos-1)] != res[fix(pos-1)]) {
                printf("-1"); return 0;
            } else {
                ans += (ll)((a[pos] - res[pos]) / around);
                a[pos] = res[pos];
            }
        } else {
            ans += (ll)(a[pos] / around); a[pos] %= around;
        }
        if (ishigh(fix(pos-1))) que.push(fix(pos-1));
        if (ishigh(fix(pos+1))) que.push(fix(pos+1));
    }
    for (int i = 1; i <= n; i++) {
        if (a[i] != res[i]) {
            printf("-1"); return 0;
        }
    }
    printf("%lld", ans);
    return 0;
}


Measured memory_bytes: 2176
#include <vector>
#include <cstdio>
#define SIZ 10
using namespace std;

const vector<pair<
	pair<int,int>,
	vector<vector<int>>
>>pattern={
	{{13,3},{
		{0,0,1,0,0},
		{0,1,1,1,0},
		{1,1,1,1,1},
		{0,1,1,1,0},
		{0,0,1,0,0},
	}},
	{{9,2},{
		{1,1,1},
		{1,1,1},
		{1,1,1},
	}},
	{{5,1},{
		{0,1,0},
		{1,1,1},
		{0,1,0},
	}},
};

int m[SIZ][SIZ];
vector<pair<pair<int,int>,int>>v;
bool dfs(int pat,int y,int x,int N,int d,int s){
	if(d==N)return s==0;
	if(s<(N-d)*5 || (N-d)*pattern[pat].first.first<s)return false;
	for(;pat<pattern.size();pat++,y=x=0)if(pattern[pat].first.first<=s){
		for(;y<=SIZ-pattern[pat].second.size();y++,x=0){
			for(;x<=SIZ-pattern[pat].second[0].size();x++){
				for(int dy=0;dy<pattern[pat].second.size();dy++){
					for(int dx=0;dx<pattern[pat].second[0].size();dx++){
						if(m[y+dy][x+dx]<pattern[pat].second[dy][dx])goto fail;
					}
				}
				for(int dy=0;dy<pattern[pat].second.size();dy++){
					for(int dx=0;dx<pattern[pat].second[0].size();dx++){
						m[y+dy][x+dx]-=pattern[pat].second[dy][dx];
					}
				}
				v[d]=make_pair(
					make_pair(x+pattern[pat].second[0].size()/2,y+pattern[pat].second.size()/2),
					pattern[pat].first.second
				);
				if(dfs(pat,y,x,N,d+1,s-pattern[pat].first.first))return true;
				for(int dy=0;dy<pattern[pat].second.size();dy++){
					for(int dx=0;dx<pattern[pat].second[0].size();dx++){
						m[y+dy][x+dx]+=pattern[pat].second[dy][dx];
					}
				}
				fail:;
			}
		}
	}
	return false;
}

int main(){
	int N,y,x,s=0;
	scanf("%d",&N);
	for(y=0;y<SIZ;y++)for(x=0;x<SIZ;x++)scanf("%d",m[y]+x),s+=m[y][x];
	v.resize(N);
	dfs(0,0,0,N,0,s);
	for(x=0;x<N;x++)printf("%d %d %d\n",v[x].first.first,v[x].first.second,v[x].second);
}

Measured memory_bytes: 1040
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <istream>
#include <sstream>
#include <cctype>
#define fore(i,x,y) for(long long i=x;i<y;i++)
typedef long long ll;
using namespace std;
int main()
{
	int a,b,f=0;
	cin >> a >> b;
	if(a%3==0&&a>=3)f=1;
	if(b%3==0&&b>=3)f=1;
	if((a+b)%3==0&&(a+b)>=3)f=1;
	if(f==1){
		cout << "Possible" << endl;
	}
	else{
		cout << "Impossible" << endl;
	}
}

Measured memory_bytes: 256
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main{
	static int n, k;
	static int[] a;

	public static void main(String[] args){
		//入力
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		a = new int[n];
		for(int i = 0; i < n; i++){
			a[i] = sc.nextInt();
		}
		sc.close();

		//処理
		Arrays.sort(a);
		int ret = binarySearch();
		int ans = 0;
		if(ret >= 0){
			ans = Math.min(n, ret + 1);
		}

		//出力
		PrintWriter out = new PrintWriter(System.out);
		out.println(ans);
		out.flush();
	}

	private static int binarySearch(){
		int ng = n; //条件を満たさない
		int ok = -1;  //条件を満たす

		while(Math.abs(ok - ng) > 1){
			int mid = (ok+ng) / 2;
			if(isOK(mid)) ok = mid;
			else ng = mid;
		}

		return ok;
	}

	static int[][] dp = new int[5010][5010];

	private static boolean isOK(int notuse){
		if(notuse >= n) return false;
		if(notuse < 0) return true;
		int kp = k - a[notuse];
		if(kp < 0) return false;
		for(int[] t : dp) Arrays.fill(t, -1);
		dp[0][0] = 1;
		List<Integer> b = new ArrayList<>();
		for(int i = 0; i < n; i++){
			if(i != notuse && a[i] < k) b.add(a[i]);
		}
		int m = b.size();

		for(int i = 0; i < m; i++){
			for(int j = 0; j < k; j++){
				if(dp[i][j] == 1){
					dp[i+1][j] = 1;
					if(j + b.get(i) < k) dp[i+1][j+b.get(i)] = 1;
				}
			}
		}

		boolean f = true;
		for(int i = kp; i < k; i++){
			if(dp[m][i] == 1) f = false;
		}

		return f;
	}
}

Measured memory_bytes: 168480
#include<iostream>
using namespace std;
int a[8005],dp[8005][16005];
int main(){
	string s;
	int x,y;
	cin>>s>>x>>y;
	int n=s.size(),k=0,w=0,ans;
	for(int i=0;i<n;i++){
		if(s[i]=='T'){
			a[++k]=w;
			w=0;
		}
		else
			w++;
	}
	a[++k]=w;
	dp[1][a[1]+8000]=1;
	for(int i=3;i<=k;i+=2)
		for(int j=0;j<=16000;j++){
			if(j+a[i]<=16000)
				dp[i][j]=dp[i-2][j+a[i]];
			if(j-a[i]>=0)
				dp[i][j]=dp[i][j]||dp[i-2][j-a[i]];
		}
	dp[0][8000]=1;
	for(int i=2;i<=k;i+=2)
		for(int j=0;j<=16000;j++){
			if(j+a[i]<=16000)
				dp[i][j]=dp[i-2][j+a[i]];
			if(j-a[i]>=0)
				dp[i][j]=dp[i][j]||dp[i-2][j-a[i]];
		}
	if(k%2==0)
		ans=dp[k][y+8000]&&dp[k-1][x+8000];
	else
		ans=dp[k][x+8000]&&dp[k-1][y+8000];
	if(ans==1)
		cout<<"Yes"<<endl;
	else
		cout<<"No"<<endl;
	return 0;
}

Measured memory_bytes: 497792
#![allow(unused_imports)]
use std::io;
use std::cmp;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::f64::consts::PI;
use std::str::FromStr;
use std::cmp::Reverse;

#[allow(dead_code)]
type Error = Box<dyn std::error::Error>;

fn read_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}

struct Scanner {
    buff: Vec<String>,
    pos: usize,
}

#[allow(dead_code)]
impl Scanner {
    pub fn new() -> Self {
        Scanner {
            buff: Vec::new(),
            pos: 0,
        }
    }

    pub fn next<T: FromStr>(&mut self) -> T {
        while self.buff.len() <= self.pos {
            self.pos = 0;
            self.buff = read_line().split_whitespace().map(|s| s.to_owned()).collect();
        }

        let result = self.buff[self.pos].parse::<T>();
        self.pos += 1;
        result.ok().unwrap()
    }

    pub fn next_line(&mut self) -> String {
        let result  = read_line().trim().to_owned();
        self.buff.clear();
        self.pos = 0;

        result
    }

    pub fn next_vec<T: FromStr>(&mut self) -> Vec<T> {
        self.buff.clear();
        self.pos = 0;
        read_line().trim().split_whitespace().map(|s| s.parse().ok().unwrap()).collect()
    }
    
    pub fn next_line_chars(&mut self) -> Vec<char> {
        let result  = read_line().trim().chars().collect();
        self.buff.clear();
        self.pos = 0;

        result
    }
}


fn main() {
    let mut sc = Scanner::new();
    let n: usize = sc.next();
    let m: usize = sc.next();

    let mut keys = Vec::with_capacity(m);
    for _i in 0..m {
        let a:u64 = sc.next();
        let _b:usize = sc.next();

        let cs: Vec<usize> = sc.next_vec();
        let mask = cs.iter().fold(0, |acc, val| acc | (1 << (val -1)));
            keys.push((a, mask));
    }
    let mut memo = vec![None; 1 << n];
    memo[0] = Some(0);

    for i in 0..1 << n {
        if let Some(c) = memo[i] {
            for &(d, mask) in keys.iter() {
                memo[i | mask] = Some(memo[i | mask].map_or(c+d, |e| cmp::min(e, c+d)));
            }
        }
    }

    if let Some(ans) = memo[(1 << n) - 1] {
        println!("{}", ans);
    } else {
        println!("-1");
    }
}


Measured memory_bytes: 2172