akhauriyash/Code-Regression huggingface dataset:
#!/usr/bin/env python3

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    V = lmi()
    C = lmi()
    diff = [V[i] - C[i] for i in range(n)]
    print(sum(filter(lambda x: x>0, diff)))


if __name__ == "__main__":
    main()


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

int main() {
	int n, a[100];
	long long int dp[100][21];
	for(int i=0; i<100; ++i) for(int j=0; j<21; ++j) dp[i][j]=0;
	cin >> n;
	for(int i=0; i<n; ++i) cin >> a[i];
	dp[0][a[0]] = 1;
	for(int i=1; i<n; ++i) {
		for(int j=0; j<=20; ++j) {
			if(j+a[i]<=20) dp[i][j+a[i]] += dp[i-1][j];
			if(j-a[i]>=0) dp[i][j-a[i]] += dp[i-1][j];
		}
	}
	cout << dp[n-1][0] << endl;
	return 0;
}

Measured memory_bytes: 1172
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cassert>
#include <climits>
#include <algorithm>
#include <string>
#include <sstream>
#include <complex>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#include <fstream>

using namespace std;
#define SZ(x) (int)(x).size()
#define REP(i,n) for(int i=0;i<(n);i++)
#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define REPR(i,n) for(int i=(n)-1;i>=0;i--)
#define ALL(s) (s).begin(), (s).end()
#define so(V) sort(ALL(V))
#define rev(V) reverse(ALL(V))
#define uni(v) v.erase( unique(ALL(v)) , v.end());

typedef long long unsigned int llu;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<bool> vb;
const double EPS = 1e-9;
const int MOD = 1e9 + 7;
const int INF = (1 << 29);
const ll LINF = 1e18;
const double PI = acos(-1);

template<typename T>vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>auto make_v(size_t a, Ts... ts) { return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...)); }
template<typename T, typename U, typename... V>
typename enable_if<is_same<T, U>::value != 0>::type
fill_v(U & u, const V... v) { u = U(v...); }
template<typename T, typename U, typename... V>
typename enable_if<is_same<T, U>::value == 0>::type
fill_v(U & u, const V... v) { for (auto& e : u) fill_v<T>(e, v...); }
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 (a > b) { a = b; return 1; } return 0; }

int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);
	int N, M;
	cin >> N >> M;
	auto S = make_v<bool > (M, N);
	vi P(M);
	REP(i, M) {
		int k;
		cin >> k;
		REP(j, k) {
			int s;
			cin >> s;
			S[i][s - 1] = true;
		}
	}
	REP(i, M) {
		cin >> P[i];
	}
	int ans = 0;
	REP(L, (1 << N)) {
		int cnt = 0;
		REP(i, M) {
			int on = 0;
			REP(j, N) {
				if (!S[i][j])continue;
				if (L >> j & 1) {
					on++;
				}
			}
			if (on % 2 == P[i])cnt++;
		}
		if (cnt == M) {
			ans++;
		}
	}
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 256
// atcoder/code-festival-2016-qualc/B/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/

#include <bits/stdc++.h>

#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))

using namespace std;

template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; }
template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; }

template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }

using lli = long long int;
using ull = unsigned long long;
using point = complex<double>;
using str = string;
template<typename T> using vec = vector<T>;

constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1});
constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1});
constexpr lli mod = 1e9 + 7;

int main(int argc, char *argv[])
{
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.setf(ios_base::fixed);
  cout.precision(15);

  int k, t;
  while (cin >> k >> t) {
    vec<int> a(t);
    cin >> a;
    sort(a.begin(), a.end());

    priority_queue<int> q;
    each (i, a) q.push(i);

    int prev = -1;
    while (q.size()) {
      if (prev == -1) {
        prev = abs(q.top());
        q.pop();
        --prev;
      } else {
        int tmp = prev;
        prev = abs(q.top());
        q.pop();
        --prev;
        if (tmp) q.push(tmp);
      }
    }
    cout << prev << endl;
  }

  return 0;
}


Measured memory_bytes: 3608
#include<stdio.h>

int main()
{
  //input
  int S, T,answer = 0;
  int left = 0, right, mid, key;
  scanf("%d", &S);
  int Ss[S];
  for(int i=0; i<S; i++) scanf("%d", &Ss[i]);
  scanf("%d", &T);
  int Tt[T];
  for(int i=0; i<T; i++) scanf("%d", &Tt[i]);
  //calc

  //actual previous search
  for(int i=0; i<T; i++)
    {
      /*
      for(int j=0; j<S; j++)
	{
	  if(Tt[i] == Ss[j])
	    {
	      answer+=1;
	      break;
	    }
	}
      */
      key = Tt[i];
      right = S;
      left = 0;
      while(left < right)
	{
	  mid = (left + right) / 2;
	  if(Ss[mid] == key)
	    {
	      answer++;
	      break;
	    }
	  else if(Ss[mid] < key) left = mid + 1;
	  else right = mid;
	}
      
    }
  
  printf("%d\n", answer);
  return 0;
  }



Measured memory_bytes: 2292
function main (input) {
    var ans = (parseInt(input.split(' ')[0],10)*100) + (parseInt(input.split(' ')[1],10)*10) + (parseInt(input.split(' ')[2],10));
    if ( ans %4 === 0 ) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Measured memory_bytes: 9420
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <utility>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <numeric> 
#define MAX_N 100
using namespace std;
typedef long long ll;
const int INF = 1<<30; 
const int MOD = 1e9 + 7;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};
int main()
{
	cin.tie(0);
	ios::sync_with_stdio(false);
	int w, h, t, p, d, c;
	while(cin >> w >> h >> t >> p, w | h | t | p)
	{
		int table[2 * MAX_N][2 * MAX_N] = {};
		for(int i = 0; i < h; i++)
			for(int j = 0; j < w; j++) table[i][j] = 1;
		for(int i = 0; i < t; i++)
		{
			cin >> d >> c;
			if(d == 1)
			{
				for(int j = 0; j < h; j++)
				{
					for(int k = 0; k < c; k++)
					{
						int alpha = c - k - 1;
						table[j][c + alpha] += table[j][k];
						table[j][k] = 0;
					}
				}
				for(int j = 0; j < MAX_N; j++)
				{
					for(int k = 0; k < MAX_N; k++)
					{
						table[j][k] = table[j][k + c];
					}
				}
			}
			else if(d == 2)
			{
				for(int j = 0; j < c; j++)
				{
					for(int k = 0; k < w; k++)
					{
						int alpha = c - j - 1;
						table[c + alpha][k] += table[j][k];
						table[j][k] = 0;
					}
				}
				for(int j = 0; j < MAX_N; j++)
				{
					for(int k = 0; k < MAX_N; k++)
					{
						table[j][k] = table[j + c][k];
					}
				}
			}
		}
		int x, y;
		for(int i = 0; i < p; i++)
		{
			cin >> x >> y;
			cout << table[y][x] << endl;
		}
	}
	return 0;
}



Measured memory_bytes: 3264
#include <iostream>

using namespace std;

int main(void) {
    int W, a, b, Wa, Wb;
    cin >> W >> a >> b;
    Wa = W + a;
    Wb = W + b;
    if(a <= b) {
        if(b <= Wa) {
            cout << 0 << endl;
        } else {
            cout << b - Wa << endl;
        }
    } else {
        if(a <= Wb) {
            cout << 0 << endl;
        } else {
            cout << a - Wb << endl;
        }
    }
    return 0;
}




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

int main(){
    int a, b;
    char op;
    
    while(1){
    cin >> a >> op >> b;
    if ( op == '+' ) cout << a + b << '\n';
    else if ( op == '-' ) cout << a - b << '\n';
    else if ( op == '*' ) cout << a * b << '\n';
    else if ( op == '/' ) cout << a / b << '\n';
    else if ( op == '?' ) break;
    
    }
    return 0;    
}



Measured memory_bytes: 3096
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Scanner; 


public class Main { 
	
    public static void main(String[] args) {
    	
    	PrintWriter out = new PrintWriter(System.out);
    	Scanner in = new Scanner(System.in);
    	new Main().solve(in, out);
    	in.close();
        out.close();
    }
    
    private void solve(Scanner in, PrintWriter out) {
    	
    	int N = in.nextInt();
    	HashMap<Integer, Integer> hash = new HashMap<Integer,Integer>();
    	for(int i=1; i<=N; i++) {
    		hash.put(i, dividedCount(i));
    	}
    	
    	List<Entry<Integer, Integer>> list_entries = new ArrayList<Entry<Integer, Integer>>(hash.entrySet());
        Collections.sort(list_entries, new Comparator<Entry<Integer, Integer>>() {
            public int compare(Entry<Integer, Integer> obj1, Entry<Integer, Integer> obj2) {
                // 4. 昇順
                return obj2.getValue().compareTo(obj1.getValue());
            }
        });
        

        System.out.println(list_entries.get(0).getKey());
    	
    	
    }
    
    private int dividedCount(int n) {
    	if(n%2!=0 || n<=1) 
    		return 0;
    	
    	return 1+dividedCount(n/2); 
    	    	
    }
   
}

Measured memory_bytes: 21844
#include <bits/stdc++.h>
using namespace std;
using pii=pair<int,int>;
using ll=long long;

#define fi first
#define se second
#define pb push_back
#define rep(i,n) for(int i=0; i<(int)(n); i++)
#define MOD 1000000007

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; }

int main() {
	int n,m;
	cin >> n >> m;
	vector<int> k(m);
	vector<int> p(m);
	vector<int> q(m);
	rep(i,m) {
		cin >> k[i];
		int temp = (1 << n) - 1;
		int temp2;
		rep(j,k[i]) {
			cin >> temp2;
			temp2--;
			p[i] += ((1 << temp2) & temp);
		}
	}
	rep(i,m) cin >> q[i];
	int ans=0;
	rep(i,(1<<n)) {
		rep(j,m) {
			if(__builtin_popcount(i & p[j]) % 2 != q[j]) break;
			if(j == m-1) ans++;
		}
	}
	cout << ans << endl;

  return 0;
}


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

using namespace std;
typedef long long ll;

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; }

int main()
{
  int N;
  cin >> N;
  
  vector<ll> A(N), M(N); 
  for(int i=0; i<N; i++)
    cin >> A[i];

  ll sum=0;
  for(int i=0; i<N; i++)
    sum += A[i];
  sum/=2;

  ll sum2=0;
  for(int i=0; i*2<N; i++)
    sum2 += A[i*2];
  
  
  M[0] = sum2-sum;
  for(int i=0; i<N-1; i++)
    {
      M[i+1]=A[i]-M[i];
    }

  
  
  
  
  
  
  for(int i=0; i<N; i++)
    cout << 2*M[i] << endl;
  

  return 0;
}


//cout << setprecision(13);
//next_permutation();
//__gcd();
//reverse();
//set ,tuple ,pair;
//bitset
//vector.find
//vector.count



Measured memory_bytes: 2944
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;

ll N, C;
ll x[100010], v[100010];
ll rx[100010], rv[100010];
ll cumL[100010], cumR[100010];
ll mxL[100010], mxR[100010];

int main() {
  cin.tie(0);
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(10);
  
  cin >> N >> C;
  for (int i = 0; i < N; i++) {
    cin >> x[i] >> v[i];
  }
  reverse_copy(x, x+N, rx);
  reverse_copy(v, v+N, rv);

  ll tmpL = 0, tmpR = 0;
  for (int i = 0; i < N; i++) {
    tmpR += v[i];
    cumR[i+1] = tmpR - x[i];
    mxR[i+1] = max(mxR[i], cumR[i+1]);
    tmpL += rv[i];
    cumL[i+1] = tmpL - (C - rx[i]);
    mxL[i+1] = max(mxL[i], cumL[i+1]);
  }
  ll ans = 0;
  for (int i = 0; i <= N; i++) {
    ans = max(ans, cumR[i] - (i == 0 ? 0 : x[i-1]) + mxL[N-i]);
    ans = max(ans, cumL[i] - (i == 0 ? 0 : (C - rx[i-1])) + mxR[N-i]);
  }
  cout << ans << endl;

  return 0;
}

Measured memory_bytes: 6528
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
 
int main() {
 
  int N,M; cin >> N >> M;
  
  vector<pair<int,string>> input(M);
  for(int i = 0; i < M; i++){
    cin >> input.at(i).first;
    cin >> input.at(i).second;
  }
  
  vector<pair<int,bool>> count(N);
  
  //inputを舐めてcountを作る
  for(int i = 0; i < M; i++){
    if(input.at(i).second == "WA" 
       && count.at(input.at(i).first - 1).second == false){
      count.at(input.at(i).first - 1).first ++;
    }else{
      count.at(input.at(i).first - 1).second = true;
    }
  }
  
  //集計 各問題を舐める
  int AC = 0; int WA = 0;
  for(int i = 0; i < N; i++){
    if(count.at(i).second){
      AC++; WA += count.at(i).first;
    }
  }

  cout << AC << " " << WA << endl;
  
  /*
  for(int i = 0; i < N; i++){
    cout << count.at(i).first << " " << count.at(i).second << ";" ;
  }
  */
}

Measured memory_bytes: 7296
#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use num::*;
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::collections::*;

fn solve() {
    input! {
        h: usize, w: usize,
        grid_a: [[usize; w]; h],
        grid_b: [[usize; w]; h],
    };

    let max_v = 80_usize * 160;
    let mut used = vec![vec![vec![false; max_v * 2 + 1]; w]; h];
    used[0][0][max_v] = true;
    let mut res = std::isize::MAX;
    for i in 0..h {
        for j in 0..w {
            let a = grid_a[i][j];
            let b = grid_b[i][j];
            // ex: max_v: 2
            // -2, -1, 0, 1, 2
            for k in 0..max_v * 2 + 1 {
                if used[i][j][k] {
                    if i == h - 1 && j == w - 1 {
                        let v = ((k + a - b) as isize - max_v as isize).abs();
                        if v < res {
                            res = v;
                        }
                        let v = ((k + b - a) as isize - max_v as isize).abs();
                        if v < res {
                            res = v;
                        }
                    }
                    if i + 1 < h {
                        let new_i = i + 1;
                        let new_j = j;
                        used[new_i][new_j][k + a - b] = true;
                        used[new_i][new_j][k + b - a] = true;
                    }
                    if j + 1 < w {
                        let new_i = i;
                        let new_j = j + 1;
                        used[new_i][new_j][k + a - b] = true;
                        used[new_i][new_j][k + b - a] = true;
                    }
                }
            }
        }
    }
    println!("{}", res);
}

fn main() {
    std::thread::Builder::new()
        .name("big stack size".into())
        .stack_size(256 * 1024 * 1024)
        .spawn(|| {
            solve();
        })
        .unwrap()
        .join()
        .unwrap();
}


Measured memory_bytes: 161356
#include <iostream>
#include <algorithm>
#include <utility>
#include <numeric>
#include <vector>
#include <array>

template <class T, class U>
inline bool chmin(T &lhs, const U &rhs) {
  if (lhs > rhs) { lhs = rhs; return true; }
  return false;
}

template <class T, class U>
inline bool chmax(T &lhs, const U &rhs) {
  if (lhs < rhs) { lhs = rhs; return true; }
  return false;
}

struct range {
  using itr = int64_t;
  struct iterator {
    itr i;
    constexpr iterator(itr i_): i(i_) { }
    constexpr void operator ++ () { ++i; }
    constexpr itr operator * () const { return i; }
    constexpr bool operator != (iterator x) const { return i != x.i; }
  };
  const iterator l, r;
  constexpr range(itr l_, itr r_): l(l_), r(std::max(l_, r_)) { }
  constexpr iterator begin() const { return l; }
  constexpr iterator end() const { return r; }
};

struct revrange {
  using itr = int64_t;
  struct iterator {
    itr i;
    constexpr iterator(itr i_): i(i_) { }
    constexpr void operator ++ () { --i; }
    constexpr itr operator * () const { return i; }
    constexpr bool operator != (iterator x) const { return i != x.i; }
  };
  const iterator l, r;
  constexpr revrange(itr l_, itr r_): l(l_ - 1), r(std::max(l_, r_) - 1) { }
  constexpr iterator begin() const { return r; }
  constexpr iterator end() const { return l; }
};

using i32 = int32_t;
using i64 = int64_t;
using u32 = uint32_t;
using u64 = uint64_t;

constexpr i32 inf32 = (i32(1) << 30) - 1;
constexpr i64 inf64 = (i64(1) << 62) - 1;

int main() {
  size_t testcases;
  std::cin >> testcases;
  auto solve = [&]() -> bool {
    size_t N;
    std::cin >> N;
    std::vector<u64> A(N);
    for (auto &x: A) {
      std::cin >> x;
    }
    std::string S;
    std::cin >> S;
    std::vector<u64> base;
    for (auto i: revrange(0, N)) {
      u64 e = A[i];
      for (auto b: base) {
        chmin(e, e ^ b);
      }
      if (S[i] == '0') {
        if (e != 0) {
          base.push_back(e);
        }
      }
      else {
        if (e != 0) {
          std::cout << "1\n";
          return 0;
        }
      }
    }
    std::cout << "0\n";
    return 0;
  };
  while (testcases--) {
    solve();
  }
  return 0;
}


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

using ll = long long;

#define rep(i, n) for (int i = 0; i < (n); ++i)
#define rrep(i, n) for (int i = 1; i <= (n); ++i)
#define drep(i, n) for (int i = (n)-1; i >= 0; --i)
#define ddrep(i, n) for (int i = n; i > 0; --i)
#define srep(i, s, t) for (int i = s; i < t; ++i)
#define ssrep(i, s, t) for (int i = s; i <= t; ++i)

#define rng(a) a.begin(), a.end()
#define rrng(a) a.rbegin(), a.rend()
#define pb push_back
#define eb emplace_back
#define fi first
#define se second

#define chmax(x, y) (x = max(x, y))
#define chmin(x, y) (x = min(x, y))

using pi = pair<int, int>;
using vi = vector<int>;
using vvi = vector<vi>;
using vl = vector<ll>;
using vvl = vector<vl>;
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;
}

template <typename T, size_t S> void printArray(const T (&array)[S]) {
  for (auto val : array)
    std::cout << val << ", ";
  std::cout << "\n";
}

const int mod = 1e9 + 7;
const int inf = 1e9 + 5;

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

  int n, w; std::cin >> n >> w;
  const int MAX = 1e5;
  vl dp(MAX+1, LONG_MAX);
  dp[0] = 0;
  int ans = 0;
  rrep(i, n) {
    int wi, v; std::cin >> wi >> v;
    ddrep(j, MAX) {
      if (j-v < 0 || dp[j-v] == LONG_MAX) continue;
      if (dp[j-v]+wi > w) continue;
      chmin(dp[j], dp[j-v]+wi);
      chmax(ans, j);
    }
  }
  std::cout << ans << "\n";
}


Measured memory_bytes: 1024
#! /usr/bin/python
# Back and Forth

"""
    −1000≦sx<tx≦1000
    −1000≦sy<ty≦1000
    sx,sy,tx,ty
    は整数である。
"""

test_mode = False

sx, sy, tx, ty = map(int, input().split())
dx = tx - sx
dy = ty - sy
abs_dx = abs(dx)
abs_dy = abs(dy)

if test_mode:
    print('dx = {}'.format(dx))
    print('dy = {}'.format(dy))
    print('abs_dx = {}'.format(abs_dx))
    print('abs_dy = {}'.format(abs_dy))


def course_type(x, y):
    """
    x, y について
        0: x,y 両方が でない
        1: x   だけが 0
        2: y   だけが 0
        3: x,y 両方が 0
    を返す。入力は絶対値でよろしく。
    """
    if x != 0 and y != 0:
        return 0
    if x == 0 and y != 0:
        return 1
    if x != 0 and y == 0:
        return 2
    return 3


def course_temp(x, y):
    """
    とりあえず (0, 0)→(x, y) の2往復のしかたを返す関数。
    x,y >= 0 とすること。※第1象限で考えるため
    """

    s = ''
    flag = course_type(x, y)

    if flag == 0: # 2点が線分上にない場合
        # ここから 1往復目
        for _ in range(x):
            s += 'R'
        for _ in range(y+1):
            s += 'U'
        for _ in range(x+1):
            s += 'L'
        for _ in range(y+1):
            s += 'D'
        s += 'R'
        # ここまで 1往復目
        # ここから 2往復目
        s += 'D'
        for _ in range(x+1):
            s += 'R'
        for _ in range(y+1):
            s += 'U'
        for _ in range(x+1):
            s += 'L'
        for _ in range(y):
            s += 'D'
        # ここまで 2往復目

    elif flag == 1:
        # ここから 1往復目
        for _ in range(y+1):
            s += 'U'
        s += 'L'
        s += 'L'
        for _ in range(y+2):
            s += 'D'
        s += 'R'
        s += 'R'
        s += 'U'
        # ここまで 1往復目
        # ここから 2往復目
        s += 'R'
        for _ in range(y):
            s += 'U'
        s += 'L'
        s += 'L'
        for _ in range(y):
            s += 'D'
        s += 'R'
        # ここまで 2往復目

    elif flag == 2:
        # ここから 1往復目
        for _ in range(y+1):
            s += 'R'
        s += 'U'
        s += 'U'
        for _ in range(y+2):
            s += 'L'
        s += 'D'
        s += 'D'
        s += 'R'
        # ここまで 1往復目
        # ここから 2往復目
        s += 'D'
        for _ in range(y):
            s += 'R'
        s += 'U'
        s += 'U'
        for _ in range(y):
            s += 'L'
        s += 'D'
        # ここまで 2往復目

    else:
        pass

    return s


def convert(s):
    """
    dx, dy の符号に応じて 文字列s を変換して返す関数
    """
    if dx >= 0:
        pass
    else:
        s.translate(str.maketrans('RL', 'LR', )) # x方向の移動を反転
    if dy >= 0:
        pass
    else:
        s.translate(str.maketrans('UD', 'DU', )) # y方向の移動を反転

    return s


def main():
    """
    全体の処理を実行する関数
    """
    course = course_temp(abs_dx, abs_dy)
    if test_mode:
        print('course:', course)

    course = convert(course)
    if test_mode:
        print('course:', course)
    print(course)


if __name__ == '__main__':
    main()


"""
参考
    Pythonで文字列を置換（replace, translate, re.sub, re.subn）
    https://note.nkmk.me/python-str-replace-translate-re-sub/
"""


Measured memory_bytes: 3192
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()   //reverse
#define strall(v) (v).cbegin(),(v).cend() //const_itterator
using namespace std;
using ll = long long;
using P = pair<int,int>;
using Graph = vector<vector<int>>;
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;}

const int INF = 1e9+5;
int main(){
  int n;
  cin >> n;
  ll res = 0;
  for(int i=1;i<=n;i++){
    if(i % 3 != 0 && i % 5 != 0 && i % 15 !=0) res+=i;
  }
  cout << res << endl;
}

Measured memory_bytes: 3636
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define fi first
#define se second
#define pb push_back
#define mk make_pair
using namespace std;
typedef long long ll;
const ll INF = 1e18;
const ll MOD = 1e9+7;
 
ll fastpowMOD(ll a, ll p,ll MOD);
ll fastpowMOD(ll a, ll p,ll MOD){ if(p==0) return 1; a %= MOD; ll z = fastpowMOD(a,p/2,MOD); z = (z*z)%MOD; if(p%2) z = (z*a)%MOD; return z; }
 
ll lcm(ll a,ll b){
	return (a*b)/__gcd(a,b);
}
 

vector<ll> adj[100000+5];
vector<ll> dp(100000+5,0);
vector<bool> vis(100000+5,false);
void dfs(ll v){
    vis[v] = true;
    vector<ll>::iterator it;
    for(it=adj[v].begin();it!=adj[v].end();it++){
        if(!vis[*it]){
          dfs(*it);
        }
        dp[v] = max(dp[v],1+dp[*it]);
      
    }

  
}


int main(){
	fastio;
  ll n,m;
  cin>>n>>m;
  
  for(ll i=0;i<m;i++){
    ll x,y;
    cin>>x>>y;
    x--;y--;
    adj[x].pb(y);
  }

  for(ll i=0;i<n;i++){
    if(!vis[i]){
      dfs(i);
    }
  }
  ll ans = 0;
  for(ll i=0;i<n;i++){
    ans = max(ans,dp[i]);
  }
  cout<<ans<<"\n";

}

Measured memory_bytes: 8576
<?php
$main = new Main();
$main->execute();

class Main {

  public function execute()
  {
    list($top, $front, $right, $left, $back, $bottom) = explode(' ', trim(fgets(STDIN)));
    $directions = str_split(trim(fgets(STDIN)));
    $dice = new Dice($top, $front, $right, $left, $back, $bottom);
    $rotater = new DiceRotater($dice);

    foreach ($directions as $direction) {
      $rotater->rotate($direction);
    }

    echo $rotater->getDice()->top."\n";
  }

}


class Dice {
  public $top;
  public $front;
  public $right;
  public $left;
  public $back;
  public $bottom;

  public function __construct($top, $front, $right, $left, $back, $bottom)
  {
    $this->top = $top;
    $this->front = $front;
    $this->right = $right;
    $this->left = $left;
    $this->back = $back;
    $this->bottom = $bottom;
  }

}

class DiceRotater {
  private $dice;

  public function __construct(Dice $dice)
  {
    $this->dice = $dice;
  }

  public function rotate($direction)
  {
    switch ($direction) {
      case ('N'):
        $this->rotateN();
        break;
      case ('S'):
        $this->rotateS();
        break;
      case ('W'):
        $this->rotateW();
        break;
      case ('E'):
        $this->rotateE();
        break;
    }
  }

  public function rotateN()
  {
    $this->dice = new Dice(
      $this->dice->front,
      $this->dice->bottom,
      $this->dice->right,
      $this->dice->left,
      $this->dice->top,
      $this->dice->back
    );
  }

  public function rotateS()
  {
    $this->dice = new Dice(
      $this->dice->back,
      $this->dice->top,
      $this->dice->right,
      $this->dice->left,
      $this->dice->bottom,
      $this->dice->front
    );
  }

  public function rotateE()
  {
    $this->dice = new Dice(
      $this->dice->left,
      $this->dice->front,
      $this->dice->top,
      $this->dice->bottom,
      $this->dice->back,
      $this->dice->right
    );
  }

  public function rotateW()
  {
    $this->dice = new Dice(
      $this->dice->right,
      $this->dice->front,
      $this->dice->bottom,
      $this->dice->top,
      $this->dice->back,
      $this->dice->left
    );
  }

  public function getDice()
  {
    return $this->dice;
  }

}

Measured memory_bytes: 15520
#include <cstdio>
#include <vector>
using namespace std;
int a[60];
vector<int> v;
long long dp[2][51][1<<18];
int main() {
	int n, k, s, t;
	scanf("%d%d%d%d", &n, &k, &s, &t);
	if ((s & t) != s) {
		puts("0");
		return 0;
	}
	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}
	for (int i = 0; i < n; i++) {
		if ((a[i] & s) == s && (a[i] | t) == t) {
			v.push_back(a[i]);
		}
	}
	int ma = (1 << 18) - 1;
	long long ans = 0;
	for (int i = 0; i < v.size(); i++) {
		dp[0][i][0] = 1;
	}
	int y = 0, z = 1;
	for (int i = 0; i < k; i++) {
		for (int j = 0; j < v.size(); j++) {
			for (int l = 0; l < 1 << 18; l++) {
				dp[z][j][l] = 0;
			}
		}
		for (int j = 0; j < v.size(); j++) {
			for (int l = 0; l < 1 << 18; l++) {
				if (dp[y][j][l] == 0) continue;
				for (int m = j + 1; m < v.size(); m++) {
					int o = v[j] & ~l, e = (ma ^ v[j]) & ~l;
					int no = o & v[m], ne = e & ~v[m];
					int nl = ma ^ no ^ ne;
					dp[z][m][nl] += dp[y][j][l];
				}
			}
			ans += dp[y][j][s^t];
		}
		for (int j = 0; j < v.size(); j++) {
			for (int l = 0; l < 1 << 18; l++) {
				dp[y][j][l] = dp[z][j][l];
			}
		}
		y = 1 - y;
		z = 1 - z;
	}
	printf("%lld\n", ans);
	return 0;
}


Measured memory_bytes: 208056
#!/usr/bin/env pypy
from __future__ import division, print_function

import os
import sys
from __builtin__ import xrange as range
from cStringIO import StringIO
from future_builtins import ascii, filter, hex, map, oct, zip
from io import IOBase

import __pypy__

from collections import Counter


def main():
    n = int(input())
    c = Counter()
    for i in range(n):
        c[''.join(sorted(input()))] += 1

    cnt = 0
    for val in c.values():
        cnt += (val * (val - 1)) >> 1

    print(cnt)


# region fastio

BUFSIZE = 8192


class FastI(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = StringIO()
        self.newlines = 0

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count("\n") + (not b)
            ptr = self._buffer.tell()
            self._buffer.seek(0,
                              2), self._buffer.write(b), self._buffer.seek(ptr)
        self.newlines -= 1
        return self._buffer.readline()


class FastO(IOBase):
    def __init__(self, file):
        self._fd = file.fileno()
        self._buffer = __pypy__.builders.StringBuilder()
        self.write = lambda s: self._buffer.append(s)

    def flush(self):
        os.write(self._fd, self._buffer.build())
        self._buffer = __pypy__.builders.StringBuilder()


def print(*args, **kwargs):
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


Measured memory_bytes: 50432
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
int main() {
    map<pair<int,int>, bool> a;
    vector<vector<int> > data(3,vector<int>(3));
    int n,b;
    int tmp;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cin >> data[i][j];
        }
    }
    cin >> n;
    for (int k = 0; k < n; k++) {
        cin >> b;
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                if (data[i][j]==b) data[i][j] = 0;
            }
        }
    }
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    int sum4 = 0;
    int sum5 = 0;
    int sum6 = 0;
    int sum7 = 0;
    int sum8 = 0;
    for (int i = 0; i < 3; i++) {
        sum1+=data[0][i];
        sum2+=data[1][i];
        sum3+=data[2][i];
        sum4+=data[i][0];
        sum5+=data[i][1];
        sum6+=data[i][2];
        sum7+=data[i][i];
        sum8+=data[i][2-i];
    }
    if (sum1 == 0 || sum2 == 0 || sum3 == 0 ||
        sum4 == 0 || sum5 == 0 || sum6 == 0 ||
        sum7 == 0 || sum8 == 0) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

Measured memory_bytes: 888
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using vin=vector<int>;
using vll=vector<long long>;
using vvin=vector<vector<int>>;
using vvll=vector<vector<long long>>;
using vstr=vector<string>;
using vvstr=vector<vector<string>>;
using vch=vector<char>;
using vvch=vector<vector<char>>;
using vbo=vector<bool>;
using vvbo=vector<vector<bool>>;
using vpii=vector<pair<int,int>>;
using pqsin=priority_queue<int,vector<int>,greater<int>>;
#define mp make_pair
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep2(i,s,n) for(int i=(s);i<(int)(n);i++)
#define all(v) v.begin(),v.end()
#define decp(n) cout<<fixed<<setprecision((int)n)
const int inf=1e9+7;
const ll INF=1e18;

int main(){
    int n,k;cin>>n>>k;
    vector<pair<ll,ll>> sushi(n);
    ll t,d;
    rep(i,n){
        cin>>t>>d;
        sushi[i]=mp(d,t);
    }
    sort(all(sushi));
    reverse(all(sushi));
    //まずおいしさが大きい順にネタが被らないようにとっていく
    set<ll> used;//そのネタを使ったかフラグ
    priority_queue<pair<ll,ll>> pq;//使わなかったものを入れていく
    priority_queue<pair<ll,ll>,vector<pair<ll,ll>>,greater<pair<ll,ll>>> ans;//各ネタのおいしさが最大のものを入れる.sizeは最大でもk
    set<pair<ll,ll>> tmp;//ansに入っているものを入れておく.用途後述
    ll sum=0;//ansに入っているもののおいしさ基礎ポイント
    rep(i,n){
        if(!used.count(sushi[i].second)){
            used.insert(sushi[i].second);
            ans.push(sushi[i]);
            sum+=sushi[i].first;
            tmp.insert(sushi[i]);
        }
        else pq.push(sushi[i]);
        if(ans.size()==k)break;//k種類目のネタのおいしさよりおいしさが小さいものをいれても満足ポイントは増えないのでここで打ち切る
    }
    ll kind=ans.size();
    while(ans.size()<k){//とりあえずansのsizeをkにして仮の答えを決めておく
        ans.push(pq.top());
        sum+=(pq.top()).first;
        pq.pop();
    }
    while(pq.size()){
        auto p=pq.top();pq.pop();
        auto q=ans.top();
        if(!tmp.count(q))break;//ansの中でおいしさが一番小さいやつのネタに関してそのネタの寿司が二種類以上あったら新しいものを加えても(ネタの種類は増えない)満足ポイントは増えない.
        //なぜならそのような場合新しく加えるやつのおいしさはansの中で最小のおいしさ以下だから.つまり, 簡単に言うとネタの種類の数が減らないなら加える意味はない.
        if(sum-q.first+(kind-1)*(kind-1)+p.first>sum+kind*kind){//加えて増加するならば加える
            ans.pop();
            ans.push(p);
            sum-=q.first;
            sum+=p.first;
            kind--;
            tmp.erase(q);
        }
        else break;//加えても増えないならそのおいしさ(p.first)より小さいおいしさの寿司については考える必要がないので打ち切る
    }
    cout<<sum+kind*kind<<endl;
}

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

using namespace std;
using ll =long long;
typedef pair<int,int> P;
#define SORT(a) sort((a).begin(),(a).end())
#define rSORT(a) reverse((a).begin(),(a).end())
#define For(i, a, b)    for(int i = (a) ; i < (b) ; ++i)
#define rep(i, n)       For(i, 0, n)
#define debug(x)  cerr << #x << " = " << (x) << endl;
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
//Write From this Line

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

	ll m = 2, M = 2;

	rep(i,k){
		if(m % a[i] != 0){
			if((m + (a[i] - (m%a[i]))) > M){
				puts("-1");
				return 0;
			}
		}
		m = (m+a[i]-1)/a[i] * a[i];
		M = floor(M / a[i]) * a[i] + a[i] - 1;
	}
	cout << m << " " << M << endl;
}


Measured memory_bytes: 1024
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <cstdio>
#include <cmath>

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

ll gcd(ll a, ll b){
    if(a<b) swap(a,b);
    if(a%b == 0) return b;
    else return gcd(b,a%b);
}
ll mod = 1000000007;
int main(){
    ll n,k; cin >> n >> k;
    ll ans = 0;
    for(ll x=k;x<=n+1;x++){
        ans += (x*(n-x+1)+1)%mod;
        ans %= mod;
    }
    cout << ans << endl;
}

Measured memory_bytes: 3644
import itertools

n = int(input())
MOD = 10 ** 9 + 7

ng_patterns3 = ['AGC', 'ACG', 'GAC']
ng_patterns4 = ['AAGC', 'AACG', 'ATGC', 'AGAC', 'AGTC', 'AGGC', 'AGCA', 'AGCT', 'AGCG', 'AGCC', 'ACGA', 'ACGT', 'ACGG',
                'ACGC', 'TAGC', 'TACG', 'TGAC', 'GAGC', 'GACA', 'GACT', 'GACG', 'GACC', 'GGAC', 'CAGC', 'CACG', 'CGAC']


# 最後の3文字が決まれば次の文字の数も決まるので、
# 最後の3文字をキーに文字列の数をカウントする
def main():
    # 初期化
    counts = {}
    for li in itertools.product('ATGC', repeat=3):
        s = ''.join(li)
        if s not in ng_patterns3:
            counts[s] = 1

    # 1文字ずつ増やす
    for _ in range(3, n):
        new_counts = {s: 0 for s in counts.keys()}
        for s3, count in counts.items():
            for c in 'ATGC':
                s4 = s3 + c
                if s4 not in ng_patterns4:
                    new_counts[s4[-3:]] += count % MOD
        counts = new_counts

    print(sum([c for c in counts.values()]) % MOD)


if __name__ == '__main__':
    main()


Measured memory_bytes: 3064
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;

int get(int a, int b) {
    return (a + b - 1) / b;
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n), b(n);
    for (int i = 0; i < n; ++i) cin >> a[i];
    for (int i = 0; i < n; ++i) b[i] = a[i];
    sort(b.begin(), b.end());
    int fm = b[n - 2], sm = b[n - 1];
    for (int i = 0; i < n; ++i) {
        if (a[i] == sm) cout << fm << endl;
        else cout << sm << endl;
    }
    return 0;
}


Measured memory_bytes: 4736
#include<stdio.h>
#include<math.h>

main(){

        int A,B,C,i;
        scanf("%d %d %d",&A,&B,&C);
        int big,mid,small,count=0;

        big = A;
        if(big<B)big = B;
        if(big<C)big = C;

        small = A;
        if(small>B)small = B;
        if(small>C)small = C;

        //printf("%d %d\n",big,small);


        if((big == A && small == B) || (big == B && small == A))mid = C;
        if((big == C && small == B) || (big == B && small == C))mid = A;
        if((big == A && small == C) || (big == C && small == A))mid = B;

        //printf("%d %d %d\n",big,mid,small);

        count += big - mid;

        if((mid-small) % 2 == 0){
                count += (mid - small) / 2;
        }

        if((mid-small) % 2 == 1){
                count += (mid -small + 1) /2 + 1;
        }




        printf("%d",count);
}


Measured memory_bytes: 128
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm> 
using namespace std;
long long x,y,maxx,s;

int main()
{
	cin>>x>>y;
	for(long long i=x;i<=y;i)
	{
		i=i*2;
		
		s++;
	}
	cout<<s;
	return 0;
} 

Measured memory_bytes: 256
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h> // uint64_t

#define BUF_SIZE 30

// size: specify sizeof(str)
int get_str(char *str, int size) {
    if(!fgets(str, size, stdin)) return -1;
    return 0;
}

int get_int(void) {
  int num;
#ifdef BUF_SIZE
  char line[BUF_SIZE];
  if(!fgets(line, BUF_SIZE, stdin)) return 0;
  sscanf(line, "%d", &num);
#else
#error
#endif
  return num;
}

int get_int2(int *a1, int *a2) {
#ifdef BUF_SIZE
  char line[BUF_SIZE];
  if(!fgets(line, BUF_SIZE, stdin)) return -1;
  sscanf(line, "%d %d", a1, a2);
#else
#error
#endif
  return 0;
}

int get_int3(int *a1, int *a2, int *a3) {
#ifdef BUF_SIZE
  char line[BUF_SIZE];
  if(!fgets(line, BUF_SIZE, stdin)) return -1;
  sscanf(line, "%d %d %d", a1, a2, a3);
#else
#error
#endif
  return 0;
}

#define PEOPLE_MAX 100000

struct ufind {
    int parent;
    int depth;
    int cnt;
};


struct ufind *create_union_find(int ps) {
    static struct ufind ufind[PEOPLE_MAX];
    int i;
    for(i = 0; i < ps; i++) {
        struct ufind *elem = &ufind[i];
        elem->parent = i;
        elem->depth = 1;
        elem->cnt = 1;
    }
    return ufind;
}

int get_root(struct ufind *ufind, int v) {
    struct ufind *uv = &ufind[v];
    int base = v;
    while(base != uv->parent) {
        base = uv->parent;
        uv = &ufind[base];
    }
    return base;
}

void connect(struct ufind *ufind, int v1, int v2) {
    int b1 = get_root(ufind, v1);
    int b2 = get_root(ufind, v2);
    // already connected
    if(b1==b2) return;
    struct ufind *ub1 = &ufind[b1];
    struct ufind *ub2 = &ufind[b2];
    ub2->cnt = ub1->cnt = ub1->cnt + ub2->cnt;
    if(ub1->depth >= ub2->depth) { // ub1 <- ub2
        if(ub1->depth == ub2->depth) ub1->depth++;
        ub2->parent = b1;
        ub2->depth = ub1->depth;
    } else {
        ub1->parent = b2;
        ub1->depth = ub2->depth;
    }
    return;
}

int get_links(struct ufind *ufind, int v) {
    struct ufind *res = &ufind[get_root(ufind, v)];
    return res->cnt;
}

int is_same(struct ufind *ufind, int v1, int v2) {
    return get_root(ufind, v1) == get_root(ufind, v2);
}

int main(void) {
    int ps, fs, bs;
    int i;
    get_int3(&ps, &fs, &bs);
    static int exclude_map[PEOPLE_MAX];
    struct ufind *ufind = create_union_find(ps);

    for(i = 0; i < fs; i++) {
        int v1, v2;
        get_int2(&v1, &v2);
        // 1-indexed -> 0-indexed
        v1--; v2--;
        exclude_map[v1]++; exclude_map[v2]++;
        connect(ufind, v1, v2);
    }

    for(i = 0; i < bs; i++) {
        int v1, v2;
        get_int2(&v1, &v2);
        // 1-indexed -> 0-indexed
        v1--; v2--;
        // v1 and v2 are both links and blocks -> not a "friend candidate"
        if(is_same(ufind, v1, v2)) {
            exclude_map[v1]++;
            exclude_map[v2]++;
        }
    }
    // print
    for(i = 0; i < ps; i++) {
        printf("%d%c", get_links(ufind, i)-1 - exclude_map[i], i==(ps-1) ? '\n' : ' ');
    }
    return 0;
}

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

int main() {
    int k;
    int x[2];
    cin >> x[0] >> x[1] >> k;
    rep(i,k) {
        if (x[i%2] % 2 == 1) x[i%2]--;
        x[i%2] /= 2;
        x[(i%2)^1] += x[i%2];
    }
    cout << x[0] << " " << x[1] << endl;
}

Measured memory_bytes: 764
#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>

#define x first
#define y second
#define ndl '\n'
#define mp make_pair
#define mt make_tuple
#define pb push_back
#define up_b upper_bound
#define low_b lower_bound
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()

using namespace std;
//using namespace __gnu_pbds;

//template<typename T> using indexed_set = tree <T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());//uniform_int_distribution<int> (l, r)

typedef long long ll;
typedef long double ld;
typedef unsigned int uint;
typedef unsigned long long ull;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef pair<int, ll> pil;
typedef pair<ll, int> pli;
typedef pair<int, ull> piu;
typedef vector<vector<int>> matrix;

const ll INF = 1e18 + 123;
const ld EPS = 1e-9;
const int inf = 1e9 + 123;
const int MOD = 1e9 + 7;
const int N = 5e5 + 123;
const int M = 1e6 + 123;
const double pi = 3.14159265359;
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};

int a[N], id[N], ans[N], p[N], sz[N];

int get(int v){
    return p[v] == v ? v : p[v] = get(p[v]);
}

void unite(int a, int b){
    a = get(a);
    b = get(b);
    if (a == b) return;
    if (sz[a] < sz[b]) swap(a, b);
    p[b] = a;
    sz[a] += sz[b];
}

void solve(){
    int n;
    cin >> n;
    for (int i = 1, x, y; i <= n; i++){
        cin >> x >> y;
        sz[i] = 1;
        id[x] = p[i] = i;
        a[x] = y;
    }
    stack<int> s;
    for (int i = 1; i <= n; i++){
        int mn = a[i];
        while (!s.empty() && a[s.top()] < a[i]){
            unite(s.top(), i);
            mn = min(mn, a[s.top()]);
            s.pop();

        }
        a[i] = mn;
        //cout << a[i] << ndl;
        s.push(i);
    }

    for (int i = 1; i <= n; i++){
        ans[id[i]] = sz[get(i)];
    }
    for (int i = 1; i <= n; i++){
        cout << ans[i] << ndl;
    }

}

int main(){
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
        freopen("output.txt", "w", stdout);
    #endif
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t = 1;
    //cin >> t;
    for (int i = 1; i <= t; i++){
        //cout << "Case #" << i << ": ";
        solve();
    }
    #ifdef KAZAKH
      //  cout << endl << 1.0 * clock() / CLOCKS_PER_SEC << endl;
    #endif
    return 0;
}


Measured memory_bytes: 7572
import java.util.Scanner;

public class Main {

	void run() {
		try (Scanner sc = new Scanner(System.in)) {
			long t = Long.parseLong(sc.next());
			int n = Integer.parseInt(sc.next());
			long[] a = new long[n];
			long[] b = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = Long.parseLong(sc.next());
				b[i] = Long.parseLong(sc.next());
			}

			int st = 0;
			long sum = 0;
			long max = 0;
			for (int i = 0; i < n; i++) {
				long ed = t + a[i];
				if (i > 0) {
					sum -= (b[i - 1] - a[i - 1]);
				}
				boolean f = false;
				for (int j = st; j < n; j++) {
					if (ed < b[j]) {
						long val = sum + (ed - a[j]);
						max = Math.max(max, val);
						st = j;
						break;
					} else if (j + 1 < n && ed <= a[j + 1]) {
						long val = sum + (b[j] - a[j]);
						max = Math.max(max, val);
						st = j;
						break;
					} else {
						sum += (b[j] - a[j]);
						if (j == n - 1) {
							f = true;
							max = Math.max(max, sum);
						}
					}
				}
				if(f) {
					break;
				}
			}

			System.out.println(max);
		}
	}

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

Measured memory_bytes: 74148