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

struct edge {int to, dist, cost;};

vector<edge> g[105];
int d[105][105];
signed main() {
	while(true) {
		int n, m, l;
		cin >> n >> m >> l;
		if(!n) break;
		for(int i=0; i<n; ++i) g[i].clear();
		for(int i=0; i<m; ++i) {
			int a, b, d, e;
			cin >> a >> b >> d >> e;
			a--, b--;
			g[a].push_back({b, d, e});
			g[b].push_back({a, d, e});
		}
		
		memset(d, 0x3f, sizeof(d));
		d[0][l] = 0;
		priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> que;
		que.push({0, 0, l});
		
		while(que.size()) {
			vector<int> v = que.top(); que.pop();
			int cost = v[0], city = v[1], money = v[2];
			//cout << cost << " " << city << " " << money << endl;
			if(d[city][money] < cost) continue;
			for(edge e: g[city]) {
				// ??????????¶????????????????
				if(e.dist <= money) {
					if(d[e.to][money-e.dist] > d[city][money]) {
						d[e.to][money-e.dist] = d[city][money];
						que.push({d[e.to][money-e.dist], e.to, money-e.dist});
					}
				}
				// ??????????¶?????????????
				if(d[e.to][money] > d[city][money] + e.cost) {
					d[e.to][money] = d[city][money] + e.cost;
					que.push({d[e.to][money], e.to, money});
				}
			}
		}
		
		int ret = 0x3f3f3f3f;
		for(int i=0; i<l+1; ++i) {
			ret = min(ret, d[n-1][i]);
			//cout << d[n-1][i] << " ";
		}
		//cout << endl;
		cout << ret << endl;
	}
	return 0;
}

Measured memory_bytes: 4296
#include <bits/stdc++.h>
#include <fstream>
#include <cstdio>
using namespace std;
// vector<pair<int,int> > v;
// cin.ignore();//twice getline(cin,s);
// g++ iterator.cpp -std=c++17
// cout<<(A + B == C ? "YES" : "NO")<<endl;
// __gcd(a,b)
// string s=to_string(n);
// string p=s.substr(0,len);
// string q=s.insert(0,str);
// sort(arr, arr+n, greater<int>());
// cout<<fixed<<setprecision(9)<<pi<<endl
// const  double pi = acos(-1.0);
// sort(v.rbegin(),v.rend());
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define vll vector<ll>
#define mll map<ll,ll >
#define mlli map<ll,ll>::iterator
#define size size()
#define endl "\n"
#define ll long long int
#define ld long double
void fast(){ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);}


int func(string &pre,string &t)
{
	int ans = 0;
	for(int i=0;i<pre.size;i++)
	{
		if(t[i]!=pre[i])
		{
			ans++;
		}
	}
	return ans;
}

int main(void)
{
	fast();

	/*
	string p = "HELLO_WORLD";
	string l = p.substr(1,1+6);
	cout<<l<<endl;
	*/

	string s,t;
	cin>>s>>t;

	int fans = INT_MAX;
	
	for(int i=0;i<=s.size-t.size;i++)
	{
		string pre = s.substr(i,(t.size));
		int x = func(pre,t);
		fans = min(fans,x);
	}	
	cout<<fans<<endl; 
}

Measured memory_bytes: 3656
def main():
    N = int(input())
    cnt = 0
    '''
    i => Aの末尾の桁が Bの先頭の桁
    j => Bの末尾の桁が Aの先頭の桁
    '''
    cnt = [[0] * 10 for _ in range(10)]
    for i in range(N+1):
        tmp = str(i)
        first = int(tmp[0])
        last = int(tmp[-1])
        cnt[first][last] += 1
    ans = 0
    for i in range(1,10):
        for j in range(1,10):
            ans += cnt[i][j] * cnt[j][i]

    print(ans)

        







if __name__ == "__main__":
    main()

Measured memory_bytes: 3064
#include<bits/stdc++.h>
#define pb emplace_back
using namespace std;
using ll = long long;
const int maxn = 300010;
const double pi = 3.1415926535897, eps = 1e-6;
#define tor(i) (pi/180*i)
signed main(){
	ios_base::sync_with_stdio(0), cin.tie(0);
	int x;
	cin >> x;
	double nx = 1, ny = 0;
	for (int i = 2, deg = x;;++i, deg += x, deg %= 360) {
		//printf("%.10f %.10f\n", nx, ny);
		//fflush(stdout);
		if (abs(nx) <= eps && abs(ny) <= eps)
			return cout << i-1 << '\n', 0;
		nx += cos(tor(deg)), ny += sin(tor(deg));
	}


		

}



Measured memory_bytes: 3988
S = gets.chomp
n = S.size

def kaibun?(str)
  str.reverse == str
end

result = [S, S[0...((n - 1) / 2)], S[((n + 1) / 2)..-1]].all? { |s| kaibun?(s) }
puts result ? 'Yes' : 'No'


Measured memory_bytes: 1788
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<algorithm>
#include<map>
#include<climits>
using namespace std;
int field[500][500],cost[500][500];
int R,W,H,X,Y;
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};

struct edge{
 int y,x,cost;
 edge(int y,int x,int cost) : y(y) , x(x) , cost(cost) {}
};
bool operator < (const edge &a,const edge &b){
 return a.cost > b.cost;
}
vector<int> dijkstra(){
 int x,y,nx,ny,rec;
 vector<int> foo(500000, INT_MAX / 4);
 foo[0] = 0;
 priority_queue<edge> que;
 for(int i = 0; i < H; i++){
  for(int j = 0; j < W; j++){
   cost[i][j] = INT_MAX;
  }
 }
 cost[Y][X] = 1;
 que.push(edge(Y,X,1));
 int rank = 0;
 foo[rank++] = 0;
 while(!que.empty()){
  edge crt = que.top();
  que.pop();
  x = crt.x;
  y = crt.y;
  foo[rank] = max(foo[rank - 1], crt.cost);
  rank++;
  if(cost[y][x] != crt.cost) continue;
  for(int i = 0; i < 4; i++){
   nx = x + dx[i];
   ny = y + dy[i];
   if(nx == -1 || ny == -1 || nx ==  W || ny == H)continue;
   rec = max(field[ny][nx], crt.cost);
   if(cost[ny][nx] > rec){
    cost[ny][nx] = rec;
    que.push(edge(ny,nx,rec));
   }
  }
 }
 return foo;
}  

int main(){
 while(scanf("%d", &R)){
  if(!R) break;
  vector<int> f(500000, INT_MAX / 2);
  vector<int> g(500000, INT_MAX / 2);
  for(int q = 0; q < 2; q++){
   scanf("%d %d %d %d", &W,&H,&X,&Y);
   X--;
   Y--;
   for(int i = 0; i < H; i++){
    for(int j = 0; j < W;j++){
     scanf("%d",&field[i][j]);
    }
   }
   if (q == 0){
       f = dijkstra();
   }
   else {
       g = dijkstra();
   }
  }
  int res = INT_MAX;
  for (int i = 0; i <= R; i++){
    res = min(res, f[i] + g[R - i]);
  }
  printf("%d\n", res);
 }
 return 0;
}

Measured memory_bytes: 9336
#include <bits/stdc++.h>
using namespace std;
int main(void){
    long long int n,a,b;
    cin>>n;
    long long int A[n];
    long long int B[n];
    for (int i=0;i<n;i++) {
        cin>>a>>b;
        A[i]=a;
        B[i]=b;
    }
    sort(A,A+n);
    sort(B,B+n,greater<long long int>());
    long long int sum=0;
    for (int i=0;i<n;i++) {
        if (i==0) {
            sum+=A[i];
        } else {
            sum+=A[i]-A[i-1];
        }
    }
    sum+=B[n-1];
    cout<<sum<<endl;
}

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

double f( double a )
{
    if( a > 0 )
        return a;
    else
        return -1 * a;
}

int main()
{
    int n, a[1000];
    double b[1000], c[1000];

    while( cin >> n )
    {
        if( n == 0 )
            break;

        double min = 100000;
        int j = 0;
        for( int i = 0; i < n; i++ )
        {
            cin >> a[i] >> b[i] >> c[i];
            if( min > f( 22 - c[i] / ( b[i] * b[i] / 10000 ) ) )
            {
                min = f( 22 - c[i] / ( b[i] * b[i] / 10000 ) );
                j = i;
            }
        }
        cout << a[j] << endl;
    }


    return 0;
}


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

int main() {
	int n, a, b;
	string s;
	cin >> n >> a >> b;
	cin >> s;
	int c1 = 0, c2 = 0;
	for (int i = 0; i < s.length(); i++) {
		switch (s[i]) {
			case 'a':
				if (c1 + c2 < a + b) {
					cout << "Yes" << endl;
					c1++;
				} else {
					cout << "No" << endl;
				}
				break;
			case 'b':
				if (c1 + c2 < a + b && c2 < b) {
					cout << "Yes" << endl;
					c2++;
				} else {
					cout << "No" << endl;
				}
				break;
			default:
				cout << "No" << endl;
				break;
		}
	}
	return 0;
}

Measured memory_bytes: 896
#include<cstdio>                                                                                                                                                        
 #include<functional>
 #include<algorithm>
 using namespace std;
 
 int main(){
 
   int x,y,n,k,ans=0;
   scanf("%d", &n);
 //  printf("%d",n);
   scanf("%d", &k);
 //  printf("%d",k);
   scanf("%d", &x);
 //  printf("%d",x);
   scanf("%d", &y);
 //  printf("%d",y);
 
   if(n>k){
     ans=k*x;
     ans+=((n-k)*y);
      printf("%d",ans);
      return 0;
    }
    ans=(n*x);
   printf("%d",ans);
    return 0;
  }

Measured memory_bytes: 128
import java.io.IOException;
import java.util.Scanner;
public class Main {

	public static void main(String[] args) throws Exception {
		// TODO ?????????????????????????????????????????????
			Scanner sc = new Scanner(System.in);
			double a = sc.nextDouble();
			double b = sc.nextDouble();
			double c = sc.nextDouble();
			double d = sc.nextDouble();
			a -= c;
			b -= d;
			a = a*a + b*b;
			a = Math.sqrt(a);
			System.out.println(a);
	}

}

Measured memory_bytes: 28072
"use strict";
function main(input) {
    const line = input.split("\n");
    let arr = line[0].split(" ");
    const N = parseInt(arr[0]);
    const M = parseInt(arr[1]);
    const A = line[1].split(" ").map(Number)
    const accum = A.reduce((Ai, x) => Ai + x)
    console.log(N < accum ? -1 : N - accum);
    return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Measured memory_bytes: 30504
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0;i < (n);i++)
#define rrep(i,n) for (int i = (n - 1);i >= 0;i--)
#define all(v) v.begin(),v.end()
using namespace std;
using ll = long long;
using P = pair<ll,ll>;
using vi = vector<int>;
using vvi = vector<vi>;

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

    int n,k;
    cin >> n >> k;
    vi a(n);
    rep(i,n) cin >> a[i];
    int ans = 0;
    while(n != 0){
        if(n > k) n = n - k + 1;
        else n = 0;
        ans++;
    }
    cout << ans << endl;
}

Measured memory_bytes: 640
dreamer = "dreamer"
eraser = "eraser"
dream = "dream"
erase = "erase"


def main():
    S = input()

    while len(S):
        lens = len(S)
        if S[-len(dreamer) :] == dreamer:
            S = S[: -len(dreamer)]
        if S[-len(eraser) :] == eraser:
            S = S[: -len(eraser)]
        if S[-len(dream) :] == dream:
            S = S[: -len(dream)]
        if S[-len(erase) :] == erase:
            S = S[: -len(erase)]
        if lens == len(S):
            print("NO")
            return
    print("YES")
    return


main()


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

#define _overload(_1,_2,_3,name,...) name
#define _rep(i,n) _range(i,0,n)
#define _range(i,a,b) for(int i=int(a);i<int(b);++i)
#define rep(...) _overload(__VA_ARGS__,_range,_rep,)(__VA_ARGS__)

#define _rrep(i,n) _rrange(i,n,0)
#define _rrange(i,a,b) for(int i=int(a)-1;i>=int(b);--i)
#define rrep(...) _overload(__VA_ARGS__,_rrange,_rrep,)(__VA_ARGS__)

#define _all(arg) begin(arg),end(arg)
#define uniq(arg) sort(_all(arg)),(arg).erase(unique(_all(arg)),end(arg))
#define getidx(ary,key) lower_bound(_all(ary),key)-begin(ary)
#define clr(a,b) memset((a),(b),sizeof(a))
#define bit(n) (1LL<<(n))
#define popcount(n) (__builtin_popcountll(n))

using namespace std;

template<class T>bool chmax(T &a, const T &b) { return (a<b)?(a=b,1):0;}
template<class T>bool chmin(T &a, const T &b) { return (b<a)?(a=b,1):0;}

using ll=long long;
using R=long double;
const R EPS=1e-9L; // [-1000,1000]->EPS=1e-8 [-10000,10000]->EPS=1e-7
inline int sgn(const R& r){return(r > EPS)-(r < -EPS);}
inline R sq(R x){return sqrt(max(x,0.0L));}

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

// Problem Specific Parameter:

const int limit = 100010;

int main(void){
	int n, s;
	cin >> n >> s;

	deque<int> deq;

	map<int, ll> num;

	rep(i, n) {
		int x, p;
		cin >> x >> p;
		num[x] = p;
		deq.push_back(x);
	}


	int last_dir = 0;
	ll ans = 0LL;

	while(1) {
		const ll head = deq.front();
		const ll tail = deq.back();
		if(s < head or tail < s) break;

		if (num[head] >= num[tail]) {
			num[head] += num[tail];
			deq.pop_back();

			if (last_dir != -1) {
				ans += abs(head - tail);
			}

			last_dir = -1;
		} else {
			num[tail] += num[head];
			deq.pop_front();

			if (last_dir != 1) {
				ans += abs(head - tail);
			}

			last_dir = 1;
		}
	}

	const ll head = deq.front();
	const ll tail = deq.back();	

	// cerr << s << " " << head << " " << tail << endl;
	ans += max(abs(s - head), abs(s - tail));

	cout << ans << endl;

	return 0;
}

Measured memory_bytes: 6912
import sys
from heapq import heappush, heappop, heapify
from pprint import pprint

N = int(sys.stdin.readline().strip())

points = []
for i in range(N):
    x, y = map(int, sys.stdin.readline().strip().split())
    points.append((i, x, y))

x_sorted = sorted(points, key=lambda x:x[1])
y_sorted = sorted(points, key=lambda x:x[2])
# pprint(x_sorted)

edges = [[] for _ in range(N)]
for i, (p1, x1, y1) in enumerate(x_sorted[:-1]):
    p2, x2, y2 = x_sorted[i+1]
    edges[p1].append((p2, x2 - x1))
    edges[p2].append((p1, x2 - x1))

for i, (p1, x1, y1) in enumerate(y_sorted[:-1]):
    p2, x2, y2 = y_sorted[i+1]
    edges[p1].append((p2, y2 - y1))
    edges[p2].append((p1, y2 - y1))

# prim法
used = set()
q = []
for i in range(N):
    if len(edges[i]):
        for t, w in edges[i]:
            q.append((w, t))
        used.add(i)
        break
heapify(q)

ans = 0
while q:
    w, s = heappop(q)
    if s in used:
        continue
    used.add(s)
    ans += w
    for t, w in edges[s]:
        if t in used:
            continue
        heappush(q, (w, t))

print(ans)

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

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

    return 0;
}


Measured memory_bytes: 3316
#include<bits/stdc++.h>
#define fi first
#define se second
#define rep(i, n) for(int (i) = 0; (i) < (n); (i)++)
#define rrep(i, n) for (int (i) = 1; (i) <= (n); (i++))
#define rng(a) a.begin(),a.end()
#define rrng(a) a.rbegin(),a.rend()
#define pb push_back
#define eb emplace_back
#define yn {puts("Yes");}else {puts("No");}
#define printd(x) printf("%.12f\n", x);
template<class T> bool chmin(T& a, const T& b) {if (a > b) {a = b; return 1;} return 0;}
template<class T> bool chmax(T& a, const T& b) {if (a < b) {a = b; return 1;} return 0;}
using namespace std;
using ll = long long;

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

	ll id;
	for (ll i = 1; i <= 10000000; i++) {
		if (i * (i+1) / 2 > n) {
			id = i;
			break;
		}
	}

	ll nouse = id * (id + 1) / 2 - n;
	for (int i = 1; i <= id; i++) {
		if (i != nouse) cout << i << endl;
	}

	return 0;
}

Measured memory_bytes: 256
import sys
INF = 1 << 60
MOD = 10**9 + 7 # 998244353
sys.setrecursionlimit(2147483647)
input = lambda:sys.stdin.readline().rstrip()
from collections import Counter
from random import randrange
def resolve():
    n = int(input())
    A = list(map(int, input().split()))
    B = list(map(int, input().split()))

    if Counter(A + B).most_common()[0][1] > n:
        print("No")
        return

    for i in range(n):
        if A[i] != B[i]:
            continue
        while 1:
            j = randrange(0, n)
            if A[i] != B[j] and A[j] != B[i]:
                B[i], B[j] = B[j], B[i]
                break
    print("Yes")
    print(*B)
resolve()

Measured memory_bytes: 52856
#include<bits/stdc++.h>
using namespace std;
const int maxn=2e5+300;
int l[maxn];
int r[maxn];
int ans;
char s[maxn];
int vis[30];
int ta;
char ts;
int cnt;
int cur;
int len;
void work()
{
    for(int i=cur; i>=0; --i) {
        memset(vis,0,sizeof(vis));
//        int now=26;
        for(int j=ta; j<=r[i]; j++)
            vis[s[j]-'a']=1;
        for(int j=0; j<26; j++)
            if(vis[j]==0) {
                printf("%c",j+'a');
                ts=j+'a';
                break;
            }
        for(int j=ta; j<=len-1; j++)if(s[j]==ts) {
                ta=j+1;
                break;
            }
    }
}
int main() {
//    freopen("in.txt","r",stdin);
    scanf("%s",s);
    len=strlen(s);
    r[0]=len-1;
    for(int i=len-1; i>=0; i--) {
        if(vis[s[i]-'a']==0) {
            cnt++;
            vis[s[i]-'a']=1;
            if(cnt==26) {
                l[cur++]=i;
                r[cur]=i-1;
                cnt=0;
                memset(vis,0,sizeof(vis));
            }
        }
    }
    l[cur]=0;
    work();
    return 0;
}
/*
abcdefghijklmnopqrstuvwxyz
*/


Measured memory_bytes: 512
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>

#define ROOP(i,n) for(i=0;i<n;i++)

//prototype declaration
int getint();
long long getllint();
double getdint();
char getch();
void setstring(char *s);
void showint(int i);
void showllint(long long i);
void showdint(double i);
void showchar(char c);
void showstring(char *s);

int myPower(int a, int n) { // aのn乗の計算
	int x = 1;
	while (n > 0) { // 全てのbitが捨てられるまで
		if ( n & 1) { // 一番右のbitが１のとき
			x *= a;
		}
		a *= a;
		n >>= 1; // bit全体を右に1つシフトして一番右を捨てる
	}
	return x;
}

int main(void) {
	int a, b;
	a = getint();
	b = getint();
	showint((a - 1) * (b - 1));
	return 0;
}

int getint() {
	int i;
	scanf("%d", &i);
	return i;
}

long long getllint() {
	long long i;
	scanf("%lld", &i);
	return i;
}

double getdint() {
	double i;
	scanf("%lf", &i);
	return i;
}

char getch() {
	char c;
	scanf("%c", &c);
	return c;
}

void setstring(char *s) {
	scanf("%s", s);
}

void showint(int i) {
	printf("%d\n", i);
}

void showllint(long long i) {
	printf("%lld\n", i);
}

void showdint(double i) {
	printf("%lf\n", i);
}

void showchar(char c) {
	printf("%c\n", c);
}

void showstring(char *s) {
	printf("%s\n", s);
}


Measured memory_bytes: 128
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
public class MainClass
{
	public const long Giri = 1000000007;
	public const long DpInf = 99999999999999;
	
	public class Part
	{
		public int Begin{get;set;}
		public int End{get;set;}
	}
	
	public static void Main(string[] args)
	{
		var n = Console.ReadLine().ToInt();
		var a = Input().ToInt();
		long money = 1000;
		
		int start = a[0];
		int begin = 0;
		var parts = new List<Part>();
		for(int i = 0; i < n; i++)
		{
			if(start > a[i])
			{
				parts.Add(new Part(){Begin = begin, End = i-1});
				begin = i;
			}
			start = a[i];
			
		}
		parts.Add(new Part(){Begin = begin, End = n-1});
		foreach(var pp in parts)
		{
			//Console.WriteLine("{0} - {1} ({2})", a[pp.Begin], a[pp.End], money);
			var cnt = (money / a[pp.Begin]);
			var m = cnt * a[pp.End];
			m += (money - (cnt * a[pp.Begin]));
			money = Math.Max(money, m);
		}
		Console.WriteLine(money);
	}
	
	static long GCD(long a, long b)
	{
		var v = new[] { a, b };
		while (v[1] != 0) { v = new[] { v[1], v[0] % v[1] }; }
		return v[0];
	}
	public static string[] Input() { return Console.ReadLine().Split(); }
}

public static class Smarter
{
	public static int ToInt(this string str) { return int.Parse(str); }
	public static long ToLong(this string str) { return long.Parse(str); }
	public static int[] ToInt(this string[] str, int offset = 0)
	{
		var r = new int[str.Length];
		for(int i = 0; i < str.Length; i++) r[i] = str[i].ToInt() + offset;
		return r;
	}
}

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

int main() {
    int n;  cin >> n;
    int r[n]; for(int i=0; i<n; i++) cin>>r[i];  
    
    int ans=-1000000000;
    int minv=r[0];
    for(int i=1; i<n; i++) {
        ans=max(ans, r[i]-minv);
        minv=min(minv, r[i]);
    }
  
  	cout << ans << endl;
}


Measured memory_bytes: 3864
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int arr[n][3];
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cin >> arr[i][j];
        }
    }
    int maxi[n][3];
    // for (int i = 0; i < n + 1; i++)
    // {
    //     cout << maxi[i] << " ";
    // }
    maxi[0][0] = arr[0][0];
    maxi[0][1] = arr[0][1];
    maxi[0][2] = arr[0][2];
    for (int i = 1; i < n; i++)
    {
        maxi[i][0] = arr[i][0] + max(maxi[i - 1][1], maxi[i - 1][2]);
        maxi[i][1] = arr[i][1] + max(maxi[i - 1][0], maxi[i - 1][2]);
        maxi[i][2] = arr[i][2] + max(maxi[i - 1][1], maxi[i - 1][0]);
    }
    cout << max(maxi[n - 1][0], max(maxi[n - 1][1], maxi[n - 1][2])) << "\n";
}

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

int main() {
  int n, m;
  scanf("%d %d", &n, &m);
  priority_queue<int> pq;
  for (int i = 0; i < n; i++) {
    int a;
    scanf("%d", &a);
    pq.push(a);
  }
  for (int i = 0; i < m; i++) {
    int a = pq.top();
    pq.pop();
    pq.push(a / 2);
  }
  long long ans = 0;
  while (!pq.empty()) {
    ans += pq.top();
    pq.pop();
  }
  printf("%lld\n", ans);
  return 0;
}

Measured memory_bytes: 892
from collections import deque

S = input().split(" ")
N = int(S[0])
M = int(S[1])
ARR = []

for i in range(M):
    ARR.append([int(s) for s in input().split(" ")])

def prepare(n, m, arr):
    nodes = [[] for i in range(n)]
    nodeStates = [0 for i in range(n)]

    for ar in arr:
        nodeFrom = ar[0] - 1
        nodeTo = ar[1] - 1
        nodes[nodeFrom].append(nodeTo)
        nodes[nodeTo].append(nodeFrom)

    return nodes, nodeStates


def bfs(startNodeIndex, arr, nodeStates):
    q = deque()

    q.append(startNodeIndex)
    nodeStates[startNodeIndex] = 1

    while q.__len__() > 0:
        nodeIndex = q.popleft()
        childNodes = arr[nodeIndex]
        for childNodeIndex in childNodes:
            if nodeStates[childNodeIndex] == 0:
                q.append(childNodeIndex)
                nodeStates[childNodeIndex] = 1

    return nodeStates


def calculate(n, m, arr):
    arr = list(arr)

    result = 0

    for ar in arr:
        brr = arr.copy()
        brr.remove(ar)

        nodes, nodeStates = prepare(n, m-1, brr)
        nodeStates = bfs(0, nodes, nodeStates)

        if sum(nodeStates) != n:
            result = result + 1

    print(result)



calculate(N, M, ARR)


Measured memory_bytes: 3316
#include<stdio.h>
#define MAX 5000



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


int f(int a[],int n){
 int t=a[0]; 
 int s=a[0];
 for(int k=1;k<n;k++){
  t=max(t+a[k],a[k]);
  s=max(s,t);
 }
 return s;
}




int main(){

 int n,i,j;
 int A[MAX];
 int ans;
 while(1)
 {

  scanf("%d",&n);
  if(n==0)break;

  for(i=0;i<n;i++)
  {
    scanf("%d",&A[i]);
  }
 ans=f(A,n);
  printf("%d\n",ans);

 }

return 0;
}


Measured memory_bytes: 1992
// Try AtCoder
// author: Leonardone @ NEETSDKASU

fn main() {
	let mut stdin = String::new();
    std::io::Read::read_to_string(
    	&mut std::io::stdin(),
        &mut stdin).unwrap();
	let mut stdin = stdin.split_whitespace();
    let mut get = || stdin.next().unwrap();
    macro_rules! get {
    	($t:ty) => (get().parse::<$t>().unwrap());
        () => (get!(i64));
    }
    
    let a = get!();
    let b = get!();
    
    let x = a * b;
    if x % 2 == 0 {
    	println!("No");
    } else {
    	println!("Yes");
    }
    
}

Measured memory_bytes: 4352
/*  UntilDeathDoesUsApart
    DO   NOT   GIVE   UP!
*/

#include <bits/stdc++.h>

using namespace std;

#define pi               acos(-1)
#define mod              1000000007
#define inc(a)           a.begin(), a.end()
#define dec(a)           a.rbegin(), a.rend()
#define Unique(n)        (n).erase(unique(inc(n)), (n).end())
#define what_is(x)       cerr << #x << " is " << x << '\n';
#define to(i, a, n)      for(int i=a; i<n; i++)
#define fr(i, a, n)      for(int i=a; i>=n; i--)
#define read(arr, l, r)  for(int i=l; i<r; cin >> arr[i++])
#define prnt(arr, l, r)  for(int i=l; i<r; cout << arr[i++] << " \n"[i==r])

typedef long long ll;
typedef long double ld;

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

    int n; cin >> n;
    cout << (n>=30 ? "Yes" : "No");

}

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

using ll=int64_t;
#define int ll

#define FOR(i,a,b) for(int i=int(a);i<int(b);i++)
#define REP(i,b) FOR(i,0,b)
#define MP make_pair
#define PB push_back
#define EB emplace_back
#define ALL(x) x.begin(),x.end()
auto& errStream=cerr;
#ifdef LOCAL
#define cerr (cerr<<"-- line "<<__LINE__<<" -- ")
#else
class CerrDummy{}cerrDummy;
template<class T>
CerrDummy& operator<<(CerrDummy&cd,const T&){
	return cd;
}
using charTDummy=char;
using traitsDummy=char_traits<charTDummy>;
CerrDummy& operator<<(CerrDummy&cd,basic_ostream<charTDummy,traitsDummy>&(basic_ostream<charTDummy,traitsDummy>&)){
	return cd;
}
#define cerr cerrDummy
#endif
#define REACH cerr<<"reached"<<endl
#define DMP(x) cerr<<#x<<":"<<x<<endl
#define ZERO(x) memset(x,0,sizeof(x))
#define ONE(x) memset(x,-1,sizeof(x))

using pi=pair<int,int>;
using vi=vector<int>;
using ld=long double;

template<class T,class U>
ostream& operator<<(ostream& os,const pair<T,U>& p){
	os<<"("<<p.first<<","<<p.second<<")";
	return os;
}

template<class T>
ostream& operator <<(ostream& os,const vector<T>& v){
	os<<"{";
	REP(i,(int)v.size()){
		if(i)os<<",";
		os<<v[i];
	}
	os<<"}";
	return os;
}

ll read(){
	ll i;
	scanf("%"  SCNd64,&i);
	return i;
}

void printSpace(){
	printf(" ");
}

void printEoln(){
	printf("\n");
}

void print(ll x,int suc=1){
	printf("%" PRId64,x);
	if(suc==1)
		printEoln();
	if(suc==2)
		printSpace();
}

string readString(){
	static char buf[3341000];
	scanf("%s",buf);
	return string(buf);
}

char* readCharArray(){
	static char buf[3341000];
	static int bufUsed=0;
	char* ret=buf+bufUsed;
	scanf("%s",ret);
	bufUsed+=strlen(ret)+1;
	return ret;
}

template<class T,class U>
void chmax(T& a,U b){
	if(a<b)
		a=b;
}

template<class T,class U>
void chmin(T& a,U b){
	if(b<a)
		a=b;
}

template<class T>
T Sq(const T& t){
	return t*t;
}

#define CAPITAL
void Yes(bool ex=true){
	#ifdef CAPITAL
	cout<<"YES"<<endl;
	#else
	cout<<"Yes"<<endl;
	#endif
	if(ex)exit(0);
}
void No(bool ex=true){
	#ifdef CAPITAL
	cout<<"NO"<<endl;
	#else
	cout<<"No"<<endl;
	#endif
	if(ex)exit(0);
}

const ll infLL=LLONG_MAX/3;

#ifdef int
const int inf=infLL;
#else
const int inf=INT_MAX/2-100;
#endif

int h,w;
char s[410][410];
bool vis[410][410];
const int dyx[]={-1,0,1,0,-1};

pi dfs(int y,int x){
	if(vis[y][x])return pi(0,0);
	vis[y][x]=true;
	pi ret(0,0);
	if(s[y][x]=='.')
		ret.first++;
	else
		ret.second++;
	REP(k,4){
		int ny=y+dyx[k],nx=x+dyx[k+1];
		if(0<=ny&&ny<h&&0<=nx&&nx<w){
			if(s[y][x]!=s[ny][nx]){
				pi waf=dfs(ny,nx);
				ret.first+=waf.first;
				ret.second+=waf.second;
			}
		}
	}
	return ret;
}

signed main(){
	h=read(),w=read();
	REP(i,h)
		scanf("%s",s[i]);
	int ans=0;
	REP(i,h)REP(j,w){
		pi waf=dfs(i,j);
		ans+=waf.first*waf.second;
	}
	print(ans);
}


Measured memory_bytes: 15616
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product, groupby, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

T = input()

ans = ""
for t in T:
	if t == "?":
		ans += "D"
	else:
		ans += t
print(ans)


Measured memory_bytes: 10852
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> P;
typedef pair<ll,ll> l_l;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<P> vp;
typedef vector<l_l> vpl;
#define pb push_back
#define sz(x) (int)(x).size()
#define fi first
#define se second
#define rep(i,n) for(int i=0;i<(n);i++)
#define rrep(i,n) for(int i=1;i<=(n);i++)
const int INF=1001001000;
const int mINF=-1001001000;
const ll LINF=10100100100100100;
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;
}
int main(){
    ll n;cin>>n;
    vl dp(n+1,LINF);
    vl h(n);
    dp[0]=0;
    rep(i,n)cin>>h[i];
    rep(i,n-1){
        dp[i+1]=min(dp[i+1],dp[i]+abs(h[i+1]-h[i]));
        if(i==n-2)continue;
        dp[i+2]=min(dp[i+2],dp[i]+abs(h[i+2]-h[i]));
    }
    cout<<dp[n-1]<<endl;
    return 0;
}

Measured memory_bytes: 1792
#include<iostream>
#include<vector>

using namespace std;

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 long long INF = 1LL << 60;

int main(void){
  long long N, M, MOD = 1000000007;
  
  cin >> N >> M;
  
  int a[M];
  long long DP[N+10];
  vector <long long> check(100010, 0);
  
  for(int i = 0; i < M; i++){
    cin >> a[i];
    check[ a[i] ] = 1;
  }
  
  for(int i = 0; i < N; i++){
    DP[i] = 0;
  }
  
  DP[0] = 1;
  if(check[1] == 0) DP[1] = 1;
  
  for(int i = 2; i < N+1; i++){
    if(check[i] == 1) continue;
    DP[i] = DP[i-1] + DP[i-2];
    DP[i] %= MOD;
  }
  
  cout << DP[N] << endl;
  
  return 0;
}



Measured memory_bytes: 2176
#include<stdio.h>
#include<string.h>
#include<math.h>
int ara[100000];
char ara1[100000];
int main()
{
    int i,j,k,a,b,l,n,t,df,v;
    while(scanf("%d %d",&a,&b)!=EOF)
    {
        v=0;
        l=a+b;
        if(a%3==0)
        {
            printf("Possible\n");
        }
        else if(b%3==0)
        {
            printf("Possible\n");
        }
        else if(l%3==0)
        {
            printf("Possible\n");
        }
        else
        {
            printf("Impossible\n");
        }
    }
    return 0;
}



Measured memory_bytes: 128
#include <iostream>
#include <cstdlib>
#include <cstdio>

using namespace std;

int top = 0, S[1001];

void push(int x)
{
    top++;
    S[top] = x;
}

int pop()
{
    return S[top--];
}

int main()
{
    char ch;
    int a = 0, b = 0;
    char s[100];
    while (scanf("%s", s) != EOF)
    {
        if (s[0] == '+')
        {
            a = pop();
            b = pop();
            push(a + b);
        }
        else if (s[0] == '-')
        {
            b = pop();
            a = pop();
            push(a - b);
        }
        else  if (s[0] == '*')
        {

            a = pop();
            b = pop();
            push(a * b);
        }else{
            push(atoi(s));
        }
    }

    cout<<pop()<<endl;

    return 0;
}


Measured memory_bytes: 3220
#include <iostream>
#include <functional>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;

int ans(int R,int G,int B,int N){
    int anse=0;
  	rep(i,N+1){
      rep(j,N+1){
        int v=N-R*i-G*j;
          if(v>=0 && v%B==0){
            anse++;
        }
        if(i*R+j*G>N)break;
      }
    if(i*R>N)break;
    }
    return anse;
}
 
 
int main() {
  int R,G,B,N;
	cin>>R>>G>>B>>N;
	cout<<ans(R,G,B,N)<<endl;
	return 0;
}

Measured memory_bytes: 3616
#include <bits/stdc++.h>
using namespace std;
#define _MACRO(_1, _2, _3, NAME, ...) NAME
#define _repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define _rep(i,n) _repl(i,0,n)
#define rep(...) _MACRO(__VA_ARGS__, _repl, _rep)(__VA_ARGS__)
#define pb push_back
#define all(x) begin(x),end(x)
#define uniq(x) sort(all(x)),(x).erase(unique(all(x)),end(x))
#ifdef LOCAL
#define dbg(...) _dbg(#__VA_ARGS__, __VA_ARGS__)
void _dbg(string){cerr<<endl;}
template<class H,class... T> void _dbg(string s,H h,T... t){int l=s.find(',');cerr<<s.substr(0,l)<<" = "<<h<<", ";_dbg(s.substr(l+1),t...);}
template<class T,class U> ostream& operator<<(ostream &o, const pair<T,U> &p){o<<"("<<p.first<<","<<p.second<<")";return o;}
template<class T> ostream& operator<<(ostream &o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}
#else
#define dbg(...) {}
#endif

int main(){
  int n,m;
  cin>>n>>m;
  vector<int> subs(n, 0);
  int ac = 0, pn = 0;
  rep(i,m) {
    int q;
    cin>>q;
    string s;
    cin>>s;
    bool ok = s == "AC";

    q--;
    if(subs[q] < 0) continue;
    if(ok){
      pn += subs[q];
      ac++;
      subs[q] = -1;
    } else {
      subs[q]++;
    }

  }
    cout << ac << " " << pn << endl;
  return 0;
}


Measured memory_bytes: 640
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

#define REP(i, n) for(int i = 0;i < n;i++)
#define REPR(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define SORT(c) sort((c).begin(),(c).end())
#define INF 999999999
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

int main()
{
	int R;
	cin >> R;

	if ( 1200 > R ) {
		cout << "ABC" << endl;
	} else if ( 2800 > R ) {
		cout << "ARC" << endl;
	} else {
		cout << "AGC" << endl;
	}
	return 0;
}


Measured memory_bytes: 256
use std::io;
use std::io::{Read, BufReader};
use std::cmp;

fn next_token<R: Read>(reader: &mut R) -> Vec<u8> {
    let mut buf: [u8; 1] = [0];
    let mut read_chars = false;
    let mut ret: Vec<u8> = vec![];

    loop {
        if reader.read(&mut buf).unwrap() == 0 {
            break;
        } else {
            if buf[0] == '\r' as u8 || buf[0] == '\n' as u8 || buf[0] == ' ' as u8 {
                if read_chars {
                    break;
                }
            } else {
                read_chars = true;
                ret.push(buf[0]);
            }
        }
    };
    ret
}
fn next_i64<R: Read>(reader: &mut R) -> i64 {
    let token = next_token(reader);
    let mut ret: i64 = 0;
    let mut sgn = false;

    for c in token {
        if '0' as u8 <= c && c <= '9' as u8 {
            ret = ret * 10 + (c - ('0' as u8)) as i64;
        } else if '-' as u8 == c {
            sgn = true;
        }
    };
    ret * if sgn { -1 } else { 1 }
}
fn next_i32<R: Read>(reader: &mut R) -> i32 {
    next_i64(reader) as i32
}
fn update(dp: &mut [bool], v: i32) {
    let mut i = dp.len() as i32 - 1 - v;
    while i >= 0 {
        if dp[i as usize] {
            dp[(i + v) as usize] = true
        }
        i -= 1;
    }
}
fn solve(k: i32, cards: &[i32], dp: [bool; 5050]) -> i32 {
    if cards.len() == 1 {
        for i in cmp::max(0, k - cards[0])..k {
            if dp[i as usize] {
                return 0
            }
        }
        1
    } else {
        let thresh = cards.len() / 2;
        let mut ret = 0;
        {
            let mut dp2 = dp;
            for i in thresh..cards.len() {
                update(&mut dp2, cards[i as usize]);
            }
            ret += solve(k, &cards[0..thresh], dp2);
        }
        {
            let mut dp2 = dp;
            for i in 0..thresh {
                update(&mut dp2, cards[i as usize]);
            }
            ret += solve(k, &cards[thresh..cards.len()], dp2);
        }
        ret
    }
}
fn main() {
    let buf = &mut BufReader::new(io::stdin());

    let n = next_i32(buf);
    let k = next_i32(buf);

    let mut cards: [i32; 5050] = [-1; 5050];
    for i in 0..n {
        cards[i as usize] = next_i32(buf);
    }
    let mut dp = [false; 5050];
    dp[0] = true;
    println!("{}", solve(k, &cards[0..(n as usize)], dp));
}


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

int inf = 1000000000;

int main(void) {
    int N,tmp;
    int ans = 0;
    cin >> N;
    vector<bool> num(inf+1,false);
    for (int i = 0; i < N; i++) {
        cin >> tmp;
        if (num[tmp])ans--;
        else ans++;
        num[tmp] = !num[tmp];
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 122368
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


def main():
    N = int(input())
    A = list(map(int, input().split()))

    que = deque()
    for i in range(N):
        if i % 2 == 0:
            que.append(A[i])
        else:
            que.appendleft(A[i])

    if N % 2 == 1:
        que.reverse()
    print(*que, sep=" ")

    
if __name__ == '__main__':
    main()


Measured memory_bytes: 25916
Q,*lrs=$<.read.split.map(&:to_i)
require 'prime'

ps = (0..10**5).map {|i| i.odd? && i.prime? && ((i+1)/2).prime? }

sum = 0
ss = []
ps.each do |p|
    sum += 1 if p
    ss << sum
end

lrs.each_slice(2) do |l,r|
    puts ss[r] - ss[l-1]
end


Measured memory_bytes: 25336
#include <stdio.h>
#include <stdlib.h>
int asc(const void *a, const void *b)
{
    return *(long int *)a - *(long int *)b;
}
int dis(const void *a, const void *b)
{
    return *(long int *)b - *(long int *)a;
}
int main()
{
    int n;
    int p;
    int ans = 0;
    int min;
    scanf("%d", &n);
    min = n + 1;
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &p);
        if (min > p)
        {
            min = p;
            ans++;
        }
    }
    printf("%d", ans);
    return 0;
}

Measured memory_bytes: 128
#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <climits>

using namespace std;

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

    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];

    int x = a[0];
    for (int i = 1; i < n; i++) x ^= a[i];

    for (int i = 0; i < n; i++) cout << (x ^ a[i]) << " ";
    cout << endl;

    return 0;
}

Measured memory_bytes: 4044
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
#include <cstring>
#include <algorithm>
#include <list>
#include <stack>
#include <queue>
using namespace std;

typedef list<int> L;
typedef pair <int,int> P;
typedef vector<int> V;
typedef queue<P> Q;
typedef stack<int> S;
typedef map<string,int> M;

const int MAX = 100;
const int INF = -1;

int h, w, d[MAX][MAX];
char f[MAX][MAX];
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};

int bfs () {
    int res = 0;
    memset(d, INF, sizeof(d));

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            if (d[i][j] == INF) {
                Q q;
                q.push(P(i,j));

                d[i][j] = res;

                while (q.size()) {
                    P p = q.front(); q.pop();
                    for (int k = 0; k < 4; k++) {
                        int nx = p.first + dx[k], ny = p.second + dy[k];
                        if (0 <= nx && nx < h && 0 <= ny && ny < w && d[nx][ny] == INF && f[p.first][p.second] == f[nx][ny]) {
                            d[nx][ny] = res;
                            q.push(P(nx,ny));
                        }
                    }
                }

                res++;
            }
        }
    }

    return res;
}

int main()
{
    while (cin >> h >> w, h) {
        for (int i = 0; i < h; i++)
            cin >> f[i];
        cout << bfs() << endl;
    }

    return 0;
}

Measured memory_bytes: 1268
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <list>

using namespace std;
#define rep(i, n) for(int i = 0; i < (int)(n); ++i)
typedef long long ll;

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> h(n);
    rep(i, n) cin >> h[i];
    sort(h.begin(),h.end());
    int ans = h[k-1] - h[0];
    rep(i, n-k+1) ans = min(ans, h[i+k-1] - h[i]);
    cout << ans << endl;
}


Measured memory_bytes: 640
#include <cstdio>
#include <algorithm>
#define maxn 200010
int a[maxn],head[maxn],tot,n,d[maxn],ans,mx[maxn];
using namespace std;
struct node{
	int to,next;
}e[maxn<<1];
void add_edge(int u,int v){
	tot++,e[tot].to=v,e[tot].next=head[u],head[u]=tot;
}
void dfs(int u,int fa){
	int b,v,save,flag,l,r,mid;;
	for(b=head[u];b;b=e[b].next){
		v=e[b].to;
		if(v==fa)continue;
		save=ans,flag=0;//回溯
		if(d[ans]<a[v])d[++ans]=a[v];
		else{
			l=0,r=ans;
			while(l+1<r){
				mid=(l+r)/2;
				if(d[mid]<a[v])l=mid;
				else r=mid;//a[st[mid]]>=a[v]
			}
			flag=d[r],d[r]=a[v];
		}
		mx[v]=ans;
		dfs(v,u);
		ans=save;//回溯
		if(flag)d[r]=flag;//回溯
	}
}
void init(){
	int i,u,v;
	scanf("%d",&n);
	for(i=1;i<=n;i++)scanf("%d",&a[i]);
	for(i=1;i<n;i++){
		scanf("%d%d",&u,&v);
		add_edge(u,v),add_edge(v,u);//无向图
	}
}
int main(){
	init();
	ans=1,d[1]=a[1],mx[1]=1;
	dfs(1,0);
	for(int i=1;i<=n;i++)printf("%d\n",mx[i]);
	return 0;
}

Measured memory_bytes: 21572
#include<iostream>
#include<string>
#include <vector>
using namespace std;
int main(){
  string S;
  cin >> S;
  int A=S[0]-'0', B=S[1]-'0', C=S[2]-'0', D=S[3]-'0';
  vector<char> v={'+', '-'};
  for(int i=0; i<2; i++){
    for(int j=0; j<2; j++){
      for(int k=0; k<2; k++){
        int sum=A;
        if(i == 0){
          sum += B;
          if(j == 0){
            sum += C;
            if(k == 0){
              sum += D;
            } else{
              sum -= D;
            }
          }else{
            sum -= C;
            if(k == 0){
              sum += D;
            } else{
              sum -= D;
            }            
          }
        }else{
          sum -= B;
                    if(j == 0){
            sum += C;
            if(k == 0){
              sum += D;
            } else{
              sum -= D;
            }
          }else{
            sum -= C;
            if(k == 0){
              sum += D;
            } else{
              sum -= D;
            }            
          }
        }
        if(sum == 7){
          cout << A << v[i] << B << v[j] << C << v[k] << D << "=7" << endl;
          return 0;
        }
      }
    }
  }
}

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

using namespace std;

#define Rep(i,a,b)  for (int i=(a);i<(b);i++)
#define rep(i,n)    for (int i=0;i<(n);i++)
#define all(x)      (x).begin(), (x).end()

#define ll long long

int main()
{
	int n, ans = 0;

	cin >> n;
	for (int i = 1; i <= n; i = i + 2) {
		map<int, int> mp;
		for (int j = 1; j <= i; j = j + 2) {
			if (i % j == 0)
				mp[j]++;
		}
		if (mp.size() == 8)
			ans++;
	}
	cout << ans << endl;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> P;
const ll MOD = 1e9+7;
const ll INF = 1e18;
#define rep(i,m,n) for(ll i = (m); i <= (n); i++)
#define rrep(i,m,n) for(ll i = (m); i >= (n); i--)
#define print(x) cout << (x) << endl;
#define printa(x,m,n) for(ll i = (m); i <= n; i++){cout << (x[i]) << " ";} cout<<endl;

ll h, w, k, s[500][500], ans[500][500];

int main(){
	cin.tie(0); ios::sync_with_stdio(false);
	
	cin >> h >> w >> k;
	rep(i, 1, h){
		string buf;
		cin >> buf;
		rep(j, 1, w){
			if(buf[j-1] == '#'){
				s[i][j] = 1;
			}	
			else{
				s[i][j] = 0;
			}
		}
	}
	
	ll num = 1;
	memset(ans, 0, sizeof(ans));
	for(ll i = 1; i <= h; i++){
		bool go = false;
		rep(gj, 1, w){if(s[i][gj] == 1){go = true;}}
		if(go){
			for(ll j = 1; j <= w; j++){
				if(ans[i][j] == 0){
					ans[i][j] = num;
					ll itigo = 0;
					if(s[i][j] == 1){itigo++;}
					ll dj = 1;
					while(ans[i][j+dj] == 0 && j+dj <= w && !(itigo >= 1 && s[i][j+dj] == 1)){
						ans[i][j+dj] = num;
						if(s[i][j+dj] == 1){itigo++;}
						dj++;
					}
					dj--;
					ll di = 1;
					while(i+di <= h){
						bool check = true;
						for(ll cj = j; cj <= j+dj; cj++){
							if(s[i+di][cj] == 1){
								check = false;
							}
						}
						if(!check){break;}
						else{
							rep(cj, j, j+dj){
								ans[i+di][cj] = num;
							}
						}
						di++;
					}
					
					di = 1;
					while(i-di >=  1){
						bool check = true;
						rep(cj, j, j+dj){
							if(s[i-di][cj] == 1 || ans[i-di][cj] != 0){
								check = false;
							}
						}
						if(!check){break;}
						else{
							rep(cj, j, j+dj){
								ans[i-di][cj] = num;
							}
						}
						di++;
					}
					
					num++;
				}
			}
		}
	}
	
	rep(i, 1, h){rep(j, 1, w){cout << ans[i][j] << " ";}cout << endl;}
	return 0;
}

Measured memory_bytes: 3968
#include<iostream>
#include<string>
#include <numeric>
#include <algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef pair<int, int> P;

int main(){
  int x, y;
  cin >> x >> y;
  for(int i=0; i<=x; i++){
    if((i*2 + (x-i)*4) == y){
      cout << "Yes" << endl;
      return 0;
    }
  }
  cout << "No" << endl;
  return 0;
}

Measured memory_bytes: 3564
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cmath>

using namespace std;


class BoxesAndCandies
{
public:
	long long n, x;
	long long sum;
	// int dp[100001][2];
	vector<long long> a;
	BoxesAndCandies();
	~BoxesAndCandies();
	void exec();
};

BoxesAndCandies::BoxesAndCandies(){
	cin >> n >> x;
	a.push_back(0);
	for (long long i = 0; i < n; ++i)
	{
		long long tmp;
		cin >> tmp;
		a.push_back(tmp);
	}
	a.push_back(0);
}

BoxesAndCandies::~BoxesAndCandies(){}

void BoxesAndCandies::exec(){
	sum = 0;
	vector<long long> b = a;
	for (int i = 1; i <= n; ++i)
	{
		if(a[i-1] + a[i] > x){
			sum += a[i] + a[i-1] - x;
			a[i] -= a[i] + a[i-1] - x;
		}
	}
	long long r_sum = 0;

	for (int i = 1; i <= n; ++i)
	{
		if(b[i+1] + b[i] > x){
			r_sum += b[i] + b[i+1] - x;
			b[i] -= b[i] + b[i+1] - x;
		}
	}
	cout << min(sum, r_sum) << endl;
}

int main(){
	BoxesAndCandies bac = BoxesAndCandies();
	bac.exec();
}


Measured memory_bytes: 1908
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <cmath>
#include <tuple>
#include <cstdio>
#include <bitset>
#include <sstream>
#include <iterator>
#include <numeric>
#include <map>
#include <cstring>
#include <set>
#include <functional>
#include <iomanip>

using namespace std;

#define DEBUG_ //!!$BDs=P;~$K%3%a%s%H%"%&%H(B!!
#ifdef DEBUG_
#define dump(x)  cerr << #x << " = " << (x) << endl;
#else
#define dump(x)  ;
#endif

#define equals(a,b) (fabs((a)-(b)) < EPS)
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)
#define SZ(x) ((int)(x).size())
#define pb push_back
#define eb emplace_back

//#define int long long

typedef long long LL;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

    template <typename T>
std::string printVector(const std::vector<T> &data)
{
    std::stringstream ss;
    std::ostream_iterator<T> out_it(ss, ", ");
    ss << "[";
    std::copy(data.begin(), data.end() - 1, out_it);
    ss << data.back() << "]";
    return ss.str();
}

template <typename T>
void print_array(const T &ary, int size){
    REP(i,size){
        cout << ary[i] << " ";
    }
    cout << endl;
}

const int mod = 1e9+7;
const LL LINF = 1001002003004005006ll;
const int INF = 1001001001;
const double EPS = (1e-10);

signed main(int argc, char const *argv[])
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << setprecision(12);

    int s; cin >> s;
    int cnt = 1;
    map<int,int> mp;
    while(1){
        if(mp.find(s) != mp.end()){
            cout << cnt << endl;
            return 0;
        }else{
            mp[s] = 1;
            if(s%2==0){
                s /= 2;
            }else{
                s = s*3+1;
            }
            cnt++;

        }
    }

}

Measured memory_bytes: 256
fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val inputs = readLine()!!.split(" ").map { it.toInt() }

    var denom = 0.0

    for ( v in inputs) {
        denom += 1.0 / v
    }

    println(1.0 / denom)

}

Measured memory_bytes: 36364