akhauriyash/Code-Regression huggingface dataset:
def binary_search(n, k, lw):
    left = 0
    right = max(lw) * n

    while left < right:
        mid = (left + right)//2
        if is_underweight(n, k, lw, p=mid):
            right = mid
        else:
            left = mid + 1

    return left

def is_underweight(n, k, lw, p):
    i = 0
    w = 0
    ck = 1
    while i < n:
        if lw[i] > p:
            return False
        rest = p - w
        if lw[i] <= rest:
            w += lw[i]
            i += 1
        else:
            w = 0
            ck += 1
    return ck <= k

def main():
    n, k = map(int, input().split())
    lw = []
    for _ in range(n):
        lw.append(int(input()))

    p = binary_search(n, k, lw)

    print(p)

if __name__ == '__main__':
    main()



Measured memory_bytes: 9560
#include <stdio.h>

int main() {
	int x1, x2, x3, x4;
	int y1, y2, y3, y4;

	scanf("%d %d %d %d", &x1, &y1, &x2, &y2);

	x3 = x2 - (y2 - y1);
	y3 = y2 - (x1 - x2);
	x4 = x3 - (y3 - y2);
	y4 = y3 - (x2 - x3);

	printf("%d %d %d %d\n", x3, y3, x4, y4);

	return 0;
}

Measured memory_bytes: 128
n=int(input())
K=list(map(int,input().split()))

dp=[float('inf') for _ in range(n)]
dp[0]=0
dp[1]=abs(K[0]-K[1])
for i in range(2,len(K)):
  dp[i]=min(dp[i-2]+abs(K[i-2]-K[i]),dp[i-1]+abs(K[i-1]-K[i]))
print(dp[-1])

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

using namespace std;

int main( ) {
    ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	t = 1;
	while(t--) {
	 int arr[3];
	 cin >> arr[0] >> arr[1] >> arr[2];
	 sort(arr, arr + 3);
	 if(arr[0] == 5 && arr[1] == 5 && arr[2] == 7)
	  cout << "YES" << endl;
	 else
	  cout << "NO" << endl;
	}
	return 0;
}



Measured memory_bytes: 256
n = int(input())
ac = wa = tle = re = 0
m = [input() for x in range(n)]
for i in range(n):
      if m[i] == "AC":
            ac += 1
      elif m[i] == "WA":
            wa += 1
      elif m[i] == "TLE":
            tle += 1
      else:
            re += 1

print("AC x " + str(ac))
print("WA x " + str(wa))
print("TLE x " + str(tle))
print("RE x " + str(re))

Measured memory_bytes: 16328
#include <cstdio>
int N;
int fuc(int x, int y, int z)
{
	return x*x+y*y+z*z+x*y+y*z+x*z;
}
int work(int n)
{
	int ans = 0;
	for(int x=1;x*x<=n;x++)
	{
		for(int y=x;y*y<=n;y++)
		{
			for(int z=y;z*z<=n;z++)
			{
				if(fuc(x, y, z)==n)
				{
					if(x!=y&&y!=z&&x!=z)
					    ans += 6;
					else if(x==y&&y==z&&x==z)
					    ans += 1;
					else
					    ans += 3;
				}
			}
		}
	}
   	return ans;
}
int main()
{
	scanf("%d", &N);
	for(int i=1;i<=N;i++)
	    printf("%d\n", work(i));
	return 0;
}

Measured memory_bytes: 1732
#include<stdio.h>
int main()
{
long double a,b;
 scanf("%Lf %Lf",&a,&b);
    if(a>b)
    {
        printf("GREATER\n");
    }
else if(a<b)
{
    printf("LESS\n");
}

else if(a=b)
{
    printf("EQUAL\n");
}



    return 0;
}


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

template <typename T> T load() { T r; cin >> r; return r; }
template <typename T> vector<T> loadMany(int n) { vector<T> rs(n); generate(rs.begin(), rs.end(), &load<T>); return rs; }

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	auto n = load<int>();
	cout << n*n*n << '\n';
}



Measured memory_bytes: 256
#include<cstdio>
#include<cstring>
#include<algorithm>
#define MAXN 100
using namespace std;
int n,a[MAXN+5],ans[MAXN+5];
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
		scanf("%d",&a[i]);
	bool legal=true;
	for(int i=n;i>=1&&legal;i--)
	{
		bool Find=false;
		for(int j=i;j>=1;j--)
			if(a[j]==j)
			{
				Find=true;
				for(int k=j;k<i;k++)
					a[k]=a[k+1];
				ans[i]=j;
				break;
			}
		if(Find==false)
			legal=false;

	}
	if(legal==false)
		printf("-1\n");
	else
		for(int i=1;i<=n;i++)
			printf("%d\n",ans[i]);
	return 0;
}

Measured memory_bytes: 128
#include<bits/stdc++.h>
using namespace std;
#define all(a)  (a).begin(),(a).end()
typedef long long ll;
const ll mod=1000000007;
#define repi(i,a,b) for(ll i=ll(a);i<ll(b);++i)

int main() {
  int n;cin >>n;
  string s,ladd="";cin>>s;
  stack<string> st;
  for(int i=0;i<n;++i){
    if(s[i]=='('){
      st.push("(");
    } else {
      if(!st.empty()){
        st.pop();
      } else {
        ladd += "(";
      }
    }
  }
  string out = ladd + s;
  for(int i=0;i<st.size();++i) out += ")";
  cout << out << endl;
  return 0;
}

Measured memory_bytes: 256
#define fi first
#define se second
#define mp make_pair
#define pb push_back

#define LOCAL 1

#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define dbg(...) cout<<#__VA_ARGS__ ": ["; for(auto e: __VA_ARGS__){cout<<e<<", ";} cout<<"]\n"
#define dbg1(...) cout<<#__VA_ARGS__ " "<< __VA_ARGS__ 
#else
#define dbg(...) 1;
#define dbg1(...) 1;
#endif

typedef long long ll;
typedef unsigned long long ull;
constexpr int R=5e6+69, INF=2e9+6969;

int qq;

int main()
{
	int n,x,ans=0;
	cin >> n;
	for(int i=1;i<=n;++i)
	{
		cin >> x;
		if(i&1 && x&1) ans++;
	}
	cout<<ans;
	return 0;
}


Measured memory_bytes: 3564
from sys import stdin


def main():
    n = int(stdin.readline().rstrip())
    ai = [int(x) for x in stdin.readline().rstrip().split()]
    ai = sorted(ai)
    ans1 = ai[-1]
    a = ans1 / 2
    before = ans1
    beforei = 0
    ans2 = ai[0]
    for i in ai[:-1]:
        d = abs(a - i)
        # print(d, i)
        if before < d:
            ans2 = beforei
            break
        before = d
        beforei = i

    print(ans1, ans2)


if __name__ == '__main__':
    main()


Measured memory_bytes: 14052
#include<stdio.h>
#include<stdlib.h>
int main(void){
	int n, k;
	int r, s, p;
	char *t;
	int *scores;
	int x = 0;
	scanf("%d", &n);
	scanf("%d", &k);
	scanf("%d", &r);
	scanf("%d", &s);
	scanf("%d", &p);
	t = (char* )malloc(sizeof(char) * (n+1));
	for(int i=0; i<n+1; i++){
		t[i] = '\0';
	}
	scores = (int* )malloc(sizeof(int) * (n+1));
	for(int j=0; j<n+1; j++){
		scores[j] = 0;
	}
	scanf("%s", t);
	for(int l=0; l<n; l++){
		if(l<k){
			if(t[l] == 'r'){
				scores[l] = p;
			}
			else if(t[l] == 's'){
				scores[l] = r;
			}
			else if(t[l] == 'p'){
				scores[l] = s;
			}
		}
		else if(l >= k){
			if(t[l] != t[l-k] || scores[l-k] == 0){
				if(t[l] == 'r'){
					scores[l] = p;
				}
				else if(t[l] == 's'){
					scores[l] = r;
				}
				else if(t[l] == 'p'){
					scores[l] = s;
				}
			}
		}
	}
	for(int m=0; m<n; m++){
		x += scores[m];
	}
	printf("%d\n", x);
	return 0;
}

Measured memory_bytes: 640
import java.util.Arrays;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		int array[] = null;
		int temp = 0;

		Scanner scanner = new Scanner(System.in);

		//入力値を扱いやすいように配列化
		for(int i = 0; scanner.hasNext(); i++) {
			if(i == 0) {
				temp = Integer.parseInt(scanner.next());
				array = new int[temp];
			}

			array[i] = Integer.parseInt(scanner.next());
		}
		
		Arrays.sort(array);
		//半分の間を求める
		System.out.println((array[(temp / 2)] - array[((temp / 2) -1)]));
	}

}

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

int main(){
  int N;
  string S,T;
  cin >> N >> S;
  T=S;
  sort(T.begin(),T.end());
  int count=0;
  for(int i=0;i<N;i++){
    if(S.at(i)!=T.at(i)){
      count++;
    }
  }
  cout << count/2 << endl;
}

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

int main() {
  long long N;
  cin >> N;
  for(long long i=sqrt(N); i>=1; i--) {
    if(N % i == 0) {
      cout << i + N / i - 2 << endl;
      return 0;
    }
  }
  return 0;
}



Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <math.h>
#include <vector>
#include <string>
#include <queue>
#include <map>
#include <utility>
#include <iomanip>  // std::setprecision()
using namespace std;
using ll = long long;
#define rep(i,a,b) for(int i=(a); i<(b); i++)
#define YES cout << "YES" << endl;
#define NO cout << "NO" << endl;
#define yes cout << "Yes" << endl;
#define no cout << "No" << endl;
#define pai 3.14159265358979323846
ll gcd(ll a, ll b){if (a%b == 0)  return(b);else  return(gcd(b, a%b));}
ll lcm(ll a, ll b){return a * b / gcd(a, b);}
/* map<string,int> */
/* 大文字を小文字に変換 tolower*/
/* 小文字を大文字に変換 toupper*/
/* 辞書順 next_permutation(a.begin(),a.end()) */

 
int main() {
    int a;
    cin >> a;
    cout << a*a*a << endl;
}


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

#define all(c) (c).begin(),(c).end()
#define FOR(i, x, n) for(int i = x; i < (int)n; i++)
#define REP(i, n) FOR(i, 0, n)
#define debug(x) #x << "=" << (x) << "(L" << __LINE__ << ")"
#define show(x) cout << #x << "=" << x << endl
#define show2(x,y) cout << #x << "=" << x << "," << #y << "=" << y <<  endl
#define show3(x,y,z) cout << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z <<  endl
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define rep1(i,n) for(int i=1;i<=(int)(n);i++)

#define ALL(x) (x).begin(),(x).end()

typedef long long ll;
typedef long double ld;
typedef vector<int> vi;

const ld eps = 1e-9, pi = acos(-1.0);
const ld EPS = 1e-8;
const int INF = INT_MAX/2;
const ll LINF = LONG_MAX/2;
const int MOD = 1000000007;

template<class T> inline void amin(T &a, const T &b) { if (b<a) a=b; }
template<class T> inline void amax(T &a, const T &b) { if (a<b) a=b; }

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(){
    
    ll a, b;
    cin >> a >> b;
    int ans = 0;
    if(a>=13){
        ans = b;
    }else if(a>=6){
        ans = b/2;
    }
	
    cout << fixed << setprecision(10);
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,N) for(int i=0;i<int(N);++i)
#define rep1(i,N) for(int i=1;i<int(N);++i)
#define all(a) (a).begin(),(a).end()
#define bit(k) (1LL<<(k))
#define SUM(v) accumulate(all(v), 0LL)

typedef pair<int, int> i_i;
typedef pair<ll, ll> l_l;
template <class T> using vec = vector<T>;
template <class T> using vvec = vector<vec<T>>;
struct fast_ios{ fast_ios(){ cin.tie(0); ios::sync_with_stdio(false); cout << fixed << setprecision(20); }; }fast_ios_;

template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

#define TOSTRING(x) string(#x)
template <typename T> istream &operator>>(istream &is, vector<T> &vec) { for (T &x : vec) is >> x; return is; }
template <typename T> ostream &operator<<(ostream &os, const vector<T> &v) { os  << "["; for(auto _: v) os << _ << ", "; os << "]"; return os; };
template <typename T> ostream &operator<<(ostream &os, set<T> &st) { os << "("; for(auto _: st) { os << _ << ", "; } os << ")";return os;}
template <typename T, typename U> ostream &operator<<(ostream &os, const pair< T, U >& p){os << "{" <<p.first << ", " << p.second << "}";return os; }
template <typename T, typename U> ostream &operator<<(ostream &os, const map<T, U> &mp){ os << "["; for(auto _: mp){ os << _ << ", "; } os << "]" << endl; return os; }

#define DUMPOUT cerr
void dump_func(){ DUMPOUT << endl; }
template <class Head, class... Tail> void dump_func(Head &&head, Tail &&... tail) { DUMPOUT << head; if (sizeof...(Tail) > 0) { DUMPOUT << ", "; } dump_func(std::move(tail)...); }

#ifdef DEBUG
#define dbg(...) dump_func(__VA_ARGS__)
#define dump(...) DUMPOUT << string(#__VA_ARGS__) << ": "; dump_func(__VA_ARGS__)
#else
#define dbg(...)
#define dump(...)
#endif

const int INF = (ll)1e9;
const ll INFLL = (ll)1e18+1;
const ll MOD = 1000000007;
// const ll MOD = 998244353;
const long double PI = acos(-1.0);

/*
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
const string dir = "DRUL";
*/

#include<atcoder/segtree>

ll op(ll a, ll b){
    return max(a, b);
}
ll e(){
    return 0;
}
const int A_MAX = 300010;
int main() {
    int N, K;
    cin >> N >> K;
    atcoder::segtree<ll, op, e> S(A_MAX);
    vector<int> A(N);
    rep(i,N)cin >> A[i];
    ll ans = 0;
    for(int i = 0; i < N; i++){
        int l = max(0, A[i] - K);
        int r = min(A_MAX-1, A[i]+K+1);
        ll prod = S.prod(l, r);
        S.set(A[i], prod+1);
        chmax(ans, prod+1);
    }
    cout << ans << endl;
}


Measured memory_bytes: 13604
#include <bits/stdc++.h>
#define rep(i,n) for(ll i=0;i<(n);++i)
#define sayyes cout<<"Yes"<<endl;
#define sayno cout<<"No"<<endl;
#define vv(a,b) vector< vector<int> > v(a,vector<int>(b,0));
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int mod =1e9+7;

int main()
{
    ll x;
    cin>>x;
    rep(i,200)
    {
        for(int j=-200;j<=200;j++)
        {
            if(pow(i,5)-pow(j,5)==x)
            {
                cout<<i<<" "<<j;
                return 0;
            }
        }
    }

}


Measured memory_bytes: 3976
#define _USE_MATH_DEFINES // for C++  
#include <cmath> 
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <array>
#include <iterator>
#include <utility>
#include <set>
#include <random>
#include <map>
#include <stack>
#include <queue>
#include <list>
#include <functional>


using namespace std;

int main() {
    char a, b;
    cin >> a >> b;
    if (a == 'H' && b == 'H')
    {
        cout << 'H' << endl;
    }
    else if (a == 'H' && b == 'D')
    {
        cout << 'D' << endl;
    }
    else if (a == 'D' && b == 'H')
    {
        cout << 'D' << endl;
    }
    else if (a == 'D' && b == 'D')
    {
        cout << 'H' << endl;
    }
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
//cervello|Phoenix
using namespace std;
#define ll long long int
#define eb emplace_back
#define mk make_pair
#define pr pair<int,int>
#define all(x) x.begin(),x.end()
#define mod 1000000007

int main(){
  ios_base::sync_with_stdio(false);
    // #ifndef ONLINE_JUDGE
    //   freopen("input.txt", "r", stdin);
    //   freopen("output.txt", "w", stdout);
    // #endif
  int n; cin>>n;
  vector<int> a(n),b(n);
  ll sum1=0,sum2=0;
  for(int i=0;i<n;i++){
    cin>>a[i];
    sum1+=a[i];
  }
  for(int i=0;i<n;i++){
    cin>>b[i];
    sum2+=b[i];
  }

  // sort(all(a));
  // sort(all(b));
  ll opr=0;
  for(int i=0;i<n;i++){
    if(a[i]<b[i]){
      opr+=(b[i]-a[i])/2+(b[i]-a[i])%2;
    }
  }
  if(opr<=(sum2-sum1)){
    cout<<"Yes\n";
  }
  else
    cout<<"No\n";
  return 0;
}

Measured memory_bytes: 384
//omajinai c++
#include <iostream>
#include<cmath>

#include<vector>
#include <algorithm>
#include <limits>
#include <numeric>
#include <type_traits>
#include <map>
#include <string>
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
constexpr auto mod = 1000000007;
using namespace std;
int main() {
	int n;
	cin >> n;
	vector<int> x(n);
	int sumx = 0;
	rep(i, n) {
		cin >> x[i];
		sumx += x[i];
	}
	int mean1 = sumx / n;
	int mean2 = mean1 + 1;

	int min1 = 0, min2 = 0;
	rep(i, n) {
		min1 += (mean1 - x[i]) * (mean1 - x[i]);
		min2 += (mean2 - x[i]) * (mean2 - x[i]);
	}

	cout << min(min1, min2);
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("03")
#pragma GCC optimize ("unroll-loops")
#define ll long long
#define ms(a,b) memset(a,b,sizeof(a))
#define endl '\n'
#define pb push_back
#define mp(a,b) make_pair(a,b)
#define mpp(a,b,c) make_pair(a,make_pair(b,c))
#define fi first
#define se second
#define rep(a,b,c) for(int a=b;a<=c;a++)
#define repp(a,b,c) for(int a=b;a>=c;a--)

int main(){
/////////////////////////////////////////////
//	ios_base::sync_with_stdio(0);
//	cin.tie(0); cout.tie(0);
/////////////////////////////////////////////
	ll a,res=1e18;
	cin >> a;
	ll sqr;
	sqr = sqrt(a);
	repp(i,sqr,1){
		if(a%i==0){
			res = min(res,abs(i-1)+abs((a/i)-1));
		}
	}
	cout << res << endl;
	return 0;
}


Measured memory_bytes: 256
from itertools import*
a,b,c,d,e,k=map(int,open(0).read().split())
x=[a,b,c,d,e]
for i in combinations(x,2):
    p,q=list(i)
    if abs(p-q)>k:
        print(":(")
        exit()
print("Yay!")

Measured memory_bytes: 3060
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Iterator;

class Graph {
	private int totalVertex;
	//adjMatrix[u][v] = 1 if there is an edge from u to v, otherwise 0
	private int[][] adjMatrix;
	//adjWeight[u][v] -- the weight of the edge from u to v if there is one
	private int[][] adjWeight;
	//if a node is settled (e.g., processed in the Dijkstra's algorithm)
	private Boolean[] ifSettled;
	public Graph() { totalVertex = 0; }
	public int getTotalVertex() { return totalVertex; }
	//load graph from standard input
	public void loadAdjMatrix() {
		Scanner in = new Scanner(System.in);
		totalVertex = in.nextInt();
		adjMatrix = new int[totalVertex][totalVertex];
		adjWeight = new int[totalVertex][totalVertex];
		ifSettled = new Boolean[totalVertex];
		int i, j;
		for(i = 0; i < totalVertex; i ++) {
			ifSettled[i] = false;
			for(j = 0; j < totalVertex; j ++) {
				adjMatrix[i][j] = adjWeight[i][j] = 0;
			}
		}
		int u, v;
		for(i = 0; i < totalVertex; i ++) {
			u = in.nextInt();
			int degree = in.nextInt();
			for(j = 0; j < degree; j ++) {
				v = in.nextInt(); 
				adjMatrix[u][v] = 1;
				adjWeight[u][v] = in.nextInt();
			}	
		}
		in.close();
	}
	//return weight of the edge from u to v if there is one
	public int getWeight(int u, int v) {
		return adjWeight[u][v];
	}
	//return neighbors of u as a LinkedList
	public LinkedList<Integer> getNeighbors(int u) {
		LinkedList<Integer> tmp = new LinkedList<Integer>();
		for(int v = 0; v < totalVertex; v ++) {
			if(adjMatrix[u][v] == 1) tmp.add(v);
		}
		return tmp;
	}
	//return unsettled neighbors of u as a LinkedList
	public LinkedList<Integer> getUnsettledNeighbors(int u) {
		LinkedList<Integer> tmp = new LinkedList<Integer>();
		for(int v = 0; v < totalVertex; v ++) {
			if((adjMatrix[u][v] == 1) && (ifSettled[v] == false)) tmp.add(v);
		}
		return tmp;
	}
	//return the unsettled node that has the smallest dist
	public int getUnsettledNearest(int[] dist) {
		int md = Integer.MAX_VALUE;
		int mv = -1;
		int v;
		for(v = 0; v < totalVertex; v ++) {
			if((ifSettled[v] == false) && (dist[v] < md)) {
				md = dist[v];
				mv = v;
			}
		}
		return mv;
	}
	//implement the following	
	public int[] Dijkstra(int s) {
		int[] distance = new int[totalVertex];
//		boolean[] sptSet = new boolean[totalVertex];
		
		for(int i = 0; i < totalVertex; i++) {
			distance[i] = Integer.MAX_VALUE;
			
		}
		distance[s] = 0;
		
		int curr = getUnsettledNearest(distance);
		while(curr != -1) {
			ifSettled[curr] = true;
			LinkedList<Integer> r = getUnsettledNeighbors(curr);
			for(Integer neighbor:r) {
				int e = getWeight(curr, neighbor);
				if(distance[neighbor] > distance[curr] + e) {
					distance[neighbor] = e + distance[curr];
				}
			}
			curr = getUnsettledNearest(distance);
		}
		return distance;
	}
}


public class Main {
	public static void main(String[] argv) {
		Graph g = new Graph();
		g.loadAdjMatrix();
		int[] dist = g.Dijkstra(0);
		for(int i = 0; i < g.getTotalVertex(); i ++) {
			System.out.println(i + " " + dist[i]);
		}
	}
}



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

using namespace std;
using ll = long long;
using vec = vector<ll>;
using mat = vector<vec>;
using pll = pair<ll,ll>;

#define INF (1LL << 60)
#define MOD 1000000007
#define PI 3.14159265358979323846

#define REP(i,m,n) for(ll (i)=(m),(i_len)=(n);(i)<(i_len);++(i))
#define FORR(i,v) for(auto (i):v)
#define ALL(x) (x).begin(), (x).end()
#define PR(x) cout << (x) << endl
#define PS(x) cout << (x) << " "
#define SZ(x) ((ll)(x).size())
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define REV(x) reverse(ALL((x)))
#define ASC(x) sort(ALL((x)))
#define DESC(x) ASC((x)); REV((x))
#define pb push_back
#define eb emplace_back

int main()
{
    ll N;
    cin >> N;
    vec T(N);
    REP(i,0,N) cin >> T[i];
    ll M;
    cin >> M;
    vec P(M), X(M);
    REP(i,0,M) cin >> P[i] >> X[i];

    ll sum = 0;
    REP(i,0,N) sum += T[i];
    REP(i,0,M) PR(sum-T[P[i]-1]+X[i]);

    return 0;
}

/*



*/

Measured memory_bytes: 3604
use std::collections::BTreeSet;

use proconio::input;

fn eval_lasts(days: i64, cs: &Vec<i64>, schedule: &Vec<BTreeSet<i64>>) -> i64 {
    let mut score = 0;

    for i in 0..cs.len() {
        let mut last = -1;

        for d in schedule[i].iter() {
            let x = d - last;
            let n = (x * (x - 1)) / 2;
            score -= cs[i] * n;
            last = *d;
        }
        let x = days - last;
        let n = (x * (x - 1)) / 2;
        score -= cs[i] * n;
    }

    score
}

fn eval(
    days: u64,
    cs: &Vec<i64>,
    sats: &Vec<Vec<i64>>,
    ts: &Vec<u64>,
) -> (i64, Vec<BTreeSet<i64>>) {
    let mut score = 0;

    let mut schedule = vec![BTreeSet::<i64>::new(); 26];

    for day in 0usize..(days as usize) {
        let contest = ts[day as usize] as usize;
        score += sats[day][contest] as i64;
        schedule[contest].insert(day as i64);
    }

    (score, schedule)
}

fn main() {
    input! { days: u64 };
    let mut cs = vec![0; 26];

    for i in 0..26 {
        input! {
            x: i64
        };

        cs[i] = x;
    }

    let mut sats = vec![vec![0; 26]; days as usize];
    for d in 0..days {
        for i in 0..26 {
            input! {
                s: i64
            };

            sats[d as usize][i as usize] = s;
        }
    }

    let mut ts = vec![0u64; days as usize];
    for i in 0..days as usize {
        input! {
            x: u64
        };

        ts[i] = x - 1;
    }

    let (mut base_score, mut schedule) = eval(days, &cs, &sats, &ts);

    input! {
        m: u64
    };
    for _ in 0..m {
        input! {
            d: usize,
            q: usize,
        };
        let d = d - 1;
        let q = q - 1;
        let prev = ts[d as usize] as usize;
        base_score -= sats[d][prev];
        base_score += sats[d][q];

        schedule[prev].remove(&(d as i64));
        schedule[q].insert(d as i64);

        let s2 = eval_lasts(days as i64, &cs, &schedule);

        println!("{}", base_score + s2);

        ts[d as usize] = q as u64;
    }
}


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

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

int room[4][3][10];

int main() {
    REP(i,4) REP(j,3) REP(k,10) room[i][j][k] = 0;
    int N; cin >> N;
    for(int i = 0, b, f, r, v; i < N; i++) {
        cin >> b >> f >> r >> v;
        b--, f--, r--;
        room[b][f][r] += v;
    }
    REP(i,4) {
        if(i > 0) cout << "####################" << endl;
        REP(j,3) {
            REP(k,10) cout << ' ' << room[i][j][k];
            cout << endl;
        }
    }
}

Measured memory_bytes: 1160
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define fastIO ios_base::sync_with_stdio(false); cin.tie(NULL);
#define ll long long int
#define pb push_back
#define mod 1000000007
#define mp make_pair
#define fi first
#define se second
int main()
{
  fastIO
  ll n,k;
  cin>>n;
  ll a[n];
  k=2;
  for(ll i=0;i<n;i++)
    cin>>a[i];
  ll dp[n];
  for(ll i=0;i<n;i++)
    dp[i]=INT_MAX;
  dp[0]=0;
  for(ll i=1;i<n;i++)
  {
    ll count=0;
    for(ll j=i-1;j>=0&&count!=k;j--)
    {
      count++;
      dp[i]=min(dp[i],(dp[j]+abs(a[i]-a[j])));
    }
  }
  /*for(ll i=0;i<n;i++)
    cout<<dp[i]<<" ";*/
  cout<<dp[n-1]<<"\n";
  return 0;
}


Measured memory_bytes: 1792
import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
  
        int h = sc.nextInt();
        int[] a = new int[h + 1];
 
        for(int i = 1; i <= h; i++) {
            a[i] = sc.nextInt();
        }
 
        for(int i = 1; i <= h; i++) {
            StringBuilder sb = new StringBuilder("node ").append(i).append(": key = ");
            sb.append(a[i]).append(", ");
            if(i >= 2) sb.append("parent key = ").append(a[i / 2]).append(", ");
            if(i * 2 <= h) sb.append("left key = ").append(a[i * 2]).append(", ");
            if(i * 2 + 1 <= h) sb.append("right key = ").append(a[i * 2 + 1]).append(", ");
            System.out.println(sb);
        }
        sc.close();
    }
}


Measured memory_bytes: 27164
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)
function main()
    L, R, d = parseMap(split(readline()))
    ans = 0
    for i in L:R
        if i % d == 0
            ans += 1
        end
    end
    println(ans)
end

main()


Measured memory_bytes: 164404
N = int(input())
H = list(map(int, input().split()))

dp = [0] * N

for i in range(1, N):
    back1 = i-1
    back2 = i-2
    min_v = 1<<30
    if back1 >= 0:
        min_v = min(dp[back1] + abs(H[i] - H[back1]), min_v)
    if back2 >= 0:
        min_v = min(dp[back2] + abs(H[i] - H[back2]), min_v)
    dp[i] = min_v

print(dp[N-1])

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

int main() {
    while (true) {
        int m, f, r;
        cin >> m >> f >> r;
        if (m == -1 && f == -1 && r == -1) break;

        char grade = 'F';
        if (m == -1 || f == -1) {
            grade = 'F';
        } else if (m + f >= 80) {
            grade = 'A';
        } else if (m + f >= 65) {
            grade = 'B';
        } else if (m + f >= 50) {
            grade = 'C';
        } else if (m + f >= 30) {
            grade = 'D';
            if (r >= 50) grade = 'C';
        }
        cout << grade << endl;
    }

    return 0;
}

Measured memory_bytes: 1152
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics;



class Myon
{
    public Myon() { }
    public static int Main()
    {
        new Myon().calc();
        return 0;
    }

    Scanner cin;
    
    void calc()
    {
        cin = new Scanner();
        int N = cin.nextInt();
        int[] A = new int[N];
        for (int i = 0; i < N; i++)
        {
            A[i] = cin.nextInt();
        }

        var a = calc2(A);
        Array.Reverse(A);
        var b = calc2(A);
        Array.Reverse(b);
        Array.Reverse(A);

        long ans = 0;
        for (int i = 0; i < N; i++)
        {
            ans += (a[i]) * (long)(b[i]) * A[i];
        }
        Console.WriteLine(ans);
    }

    int[] calc2(int[] A)
    {
        int[] ans = new int[A.Length];
        int N = A.Length;
        int[] num = new int[N + 1];
        int[] pos = new int[N + 1];
        int cnt = 0;
        num[0] = -1;
        pos[0] = -1;


        for (int i = 0; i < A.Length; i++)
        {
            while (num[cnt] > A[i]) cnt--;
            ans[i] = i - pos[cnt];
            cnt++;
            num[cnt] = A[i];
            pos[cnt] = i;
        }
        return ans;
    }


        
}


class Scanner
{
    string[] s;
    int i;

    char[] cs = new char[] { ' ' };

    public Scanner()
    {
        s = new string[0];
        i = 0;
    }

    public string next()
    {
        if (i < s.Length) return s[i++];
        string st = Console.ReadLine();
        while (st == "") st = Console.ReadLine();
        s = st.Split(cs, StringSplitOptions.RemoveEmptyEntries);
        if (s.Length == 0) return next();
        i = 0;
        return s[i++];
    }

    public int nextInt()
    {
        return int.Parse(next());
    }
    public int[] ArrayInt(int N, int add = 0)
    {
        int[] Array = new int[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextInt() + add;
        }
        return Array;
    }

    public long nextLong()
    {
        return long.Parse(next());
    }

    public long[] ArrayLong(int N, long add = 0)
    {
        long[] Array = new long[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextLong() + add;
        }
        return Array;
    }

    public double nextDouble()
    {
        return double.Parse(next());
    }


    public double[] ArrayDouble(int N, double add = 0)
    {
        double[] Array = new double[N];
        for (int i = 0; i < N; i++)
        {
            Array[i] = nextDouble() + add;
        }
        return Array;
    }
}
 

Measured memory_bytes: 32476
#include <iostream>
#include <cstring>
#include <map>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <set>
#include <vector>
#include <queue>
#include <list>
#include <numeric>
#include <stdio.h>
#include <string>
#include <cstdlib>
#include <math.h>
#include <stack>
#include <climits>
#include <bitset>
#include <utility>


using namespace std;
typedef long long ll;

//最小公倍数
ll gcd(ll x, ll y) {
  ll tmp = 0;
  if (x < y){
    tmp=x;
    x=y;
    y=tmp;
  }
  while (y > 0) {
    ll r = x % y;
    x = y;
    y = r;
  }
  return x;
}

//最大公倍数
ll lcm(ll x,ll y){
  return x/gcd(x,y)*y;
}

//階乗
ll kaijo(ll k){
    ll sum = 1;
    for (ll i = 1; i <= k; ++i)
    {
        sum *= i;
        sum%=1000000000+7;
    }
    return sum;
}

//for(int i = ; i < ; i++){}

ll lmax(ll s,ll t){
  if(s>t){
    return s;
  }
  else{
    return t;
  }
}

ll lmin(ll s,ll t){
  if(s<t){
    return s;
  }
  else{
    return t;
  }
}
// ここから開始

int main(){
  int n;
  cin>>n;
  int f[n][10];
  int p[n][11];
  for(int i = 0; i < n; i++){
    for(int j = 0; j < 10; j++){
      cin>>f[i][j];
    }
  }
  for(int i = 0; i < n; i++){
    for(int j = 0; j < 11; j++){
      cin>>p[i][j];
    }
  }
  
  int ans = -(1<<30);
  for(int i = 1; i <(1<<10); i++){
    int tmpans = 0;
    
    for(int j = 0; j < n; j++){
      int cnt = 0;//かぶった営業時間帯を数える
      for(int k = 0; k < 10; k++){
        if((i&(1<<k))&&f[j][k]) cnt++;
      }
      tmpans+=p[j][cnt];
      
    }
    
    ans = max(ans,tmpans);
    //  cout<<bitset<10>(i)<<" "<<tmpans<<endl;
  }
  cout<<ans<<endl;
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
typedef long long ll;
typedef long double ld;
#define pb push_back

using namespace std;

int main()
{
   FAST/**/
    
   ll n,k;
   cin>>n>>k;
   
   ll arr[n];
   for(ll i=0;i<n;i++)
        cin>>arr[i];
   
   ll sum = 0;
   //sum = accumulate(arr,arr+n,sum);
   //cout<<sum;
   for(ll i=0;i<n;i++)      
        sum+=arr[i];
   vector<ll> hold;
   for(ll i=1;i<=sqrt(sum);i++)
   {
       if(sum%i == 0)
       {
           hold.pb(i);
           if(i!= (sum/i))
                hold.pb(sum/i);
       }
   }
   
   sort(hold.begin(), hold.end());
   //cout<<sum<<"\n"
   ll ans = 1;
   for(ll i=0;i<hold.size();i++)
   {
        vector<ll> fin;
        for(ll i1=0;i1<n;i1++)
            fin.pb(arr[i1]%hold[i]);
        ll sum = 0;
        for(ll i=0;i<n;i++)
            sum+=fin[i];
        ll cs = 0;   
        sort(fin.begin(), fin.end());
        ll mini = 0;
        for(ll i=0;i<n-1;i++)
            mini+=fin[i];
        for(ll i1=0;i1<n-1;i1++)
        {
            cs+=fin[i1];
            ll cnt = n-1-i1;
            cnt*=hold[i];
            cnt-=(sum-cs);
            if(cs == cnt)
                mini = min(mini,cs);
        }
        
        if(mini<=k)
            ans = hold[i];
   }
   
   cout<<ans;
   
   return 0;
}

Measured memory_bytes: 256
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    while (N > 0) {
      if (N % 10 == 7) {
        System.out.println("Yes");
        return;
      }
      N /= 10;
    }
    System.out.println("No");
  }
}


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


int main()
{
	int a;
	string s,t;
	stringstream ss;
	cin>>s>>t;
	s+=t;
	ss<<s;
	ss>>a;
	for(int i=1;i*i<=a;i++)
	{
		if(i*i==a)
		{
			cout<<"Yes"<<endl;
			return 0;
		}
	}
	cout<<"No"<<endl;
	return 0;
}

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

namespace ConsoleApp3
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var days = int.Parse(Console.ReadLine());

            var scoreDownCoefficients = Console.ReadLine().Split(" ")
                .Select(int.Parse)
                .ToArray();

            foreach (var i in Enumerable.Range(2, days))
            {
                var scoreUpNumber = Console.ReadLine().Split(" ")
                    .Select((x, i) => (score: int.Parse(x), dayNumber: i + 1))
                    .OrderByDescending(x => x.score)
                    .First().dayNumber;

                Console.WriteLine(scoreUpNumber);
            }
        }
    }
}


Measured memory_bytes: 29100
n = int(input())
alist = []
blist = []
for i in range(n):
  a,b = map(int, input().split(" "))
  alist.append(a)
  blist.append(b)

alist.sort(reverse=False) 
blist.sort(reverse=False) 

if n%2 == 0:
  amedian = (alist[int(n/2-1)]+alist[int(n/2)])/2
  bmedian = (blist[int(n/2-1)]+blist[int(n/2)])/2
  print(int((bmedian-amedian)*2+1))
if n%2 == 1:
  amedian = alist[int((n-1)/2)]
  bmedian = blist[int((n-1)/2)]
  print(int((bmedian-amedian)+1))

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

#define ll long long int


int main() {
    ll n;
    cin>>n;
    unordered_map<ll, ll> umap;
    for(ll i = 0; i < n; i++){
        ll temp;
        cin>>temp;
        umap[temp]++;
    }
    ll extra = 0;
    for(auto x : umap){ // never write auto with while it should be written with for
        if(x.first == x.second)
            extra += 0;
        else if(x.first > x.second)
            extra += x.second;
        else
            extra += (x.second - x.first);
        
    }
    cout<<extra<<endl;
    
    
    return 0;
}

Measured memory_bytes: 7152
from bisect import bisect_left
from collections import deque
N = int(input())
A = [int(input()) for i in range(N)]
cnt, ms, flag = 1, deque(), 1
ms.append(A[0])
for a in A[1:]:
    if a <= ms[0]:
        ms.appendleft(a)
        cnt += 1
    else:
        i = bisect_left(ms, a)-1
        ms[i] = a
print(cnt)


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

#define deb(x) cout << #x << "=" << x << endl
#define ll long long

const int mod = 1000000007;
const int N = 3e5, M = N;

void solve() {
	ll a, b, n, W;
	ll input;
	cin >> n >> W;
	vector<ll> wt(n);
	vector<ll> val(n);
	for (int i = 0; i < n; i++)
	{
		cin >> wt[i] >> val[i];
	}
	// cout << endl;
	ll dp[n + 1][W + 1];
	for (ll i = 0; i <= n; i++)
	{
		for (ll j = 0; j <= W; j++)
		{
			if (i == 0 || j == 0)
				dp[i][j] = 0;
			else if (wt[i - 1] > j)
				dp[i][j] = dp[i - 1][j];
			else
				dp[i][j] = max(val[i - 1] + dp[i - 1][j - wt[i - 1]], dp[i - 1][j]);
		}
	}

	cout << dp[n][W] << endl;














}



int main() {
	ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	srand(chrono::high_resolution_clock::now().time_since_epoch().count());
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	ll t = 1;
	// cin >> t;
	while (t--) {
		solve();
	}

	return 0;
}



Measured memory_bytes: 82480
fn main() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();
    let k: usize = sc.read();

    let prefix = (n + 1) / 2;
    let suffix = n / 2;

    let mut a = vec![0; n];
    let mut b = vec![0; n];
    for i in 0..prefix {
        a[prefix - 1 - i] = k + i;
    }
    for i in 0..suffix {
        a[n - 1 - i] = k + i + prefix;
    }
    for i in 0..prefix {
        b[i] = k + n + i * 2;
    }
    for i in 0..suffix {
        b[i + prefix] = k + n + i * 2 + 1;
    }

    let mut ans = vec![];
    for i in 0..n {
        let a = a[i];
        let b = b[i];
        let c = k + n * 2 + i;
        if a + b <= c {
            ans.push((a, b, c));
        } else {
            println!("-1");
            return;
        }
    }

    for (a, b, c) in ans.into_iter() {
        sc.write(format!("{} {} {}\n", a, b, c));
    }
}

/// 22 26
/// 21 28
/// 20 30
/// 25 27
/// 24 29
/// 23 31

/// (m+1)
/// a   b
/// a-1 b+2
/// a-2 b+4
/// a-3 b+6
/// a-m b+2m    =   a+b+m
///
/// m
/// a+m b+1     =   a+b+m+1,    a+m
/// a+m-1 b+3
/// z-2 b+5
/// z-3 b+7
/// ...
/// a+m-(m+1)    b+2(m-1)+1
///
///
/// a   b
/// a-1 b+2
/// a-2 b+4
/// a-3 b+6
/// ...
/// a-(m-1) b+2(m-1)    =   a+b+m-1
///
/// m
/// z b+1     =   z+b+1 = a+b+m => z=a+m-1
/// z-1 b+3
/// z-2 b+5
/// z-3 b+7
/// ...
/// z-(m-1) b+2(m-1)+1   z-(m-1) = a

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}


Measured memory_bytes: 13300
#[allow(dead_code)]

pub struct Scanner {
    idx: usize, 
    buf: Vec<String>,
}

impl Scanner {
    pub fn new<T: std::io::Read>(inf: &mut T) -> Scanner {
        Self {
            idx:0,
            buf: {
                let mut s = String::new();
                inf.read_to_string(&mut s).expect("I/O error");
                s.split_whitespace().map(|x| x.to_owned()).collect()
            },
        }
    }

    pub fn read<T: std::str::FromStr> (&mut self) -> T 
    where
        <T as std::str::FromStr>::Err: std::fmt::Debug,
    {
        if self.empty() {
            panic!("reached the end of input")
        }
        let ret = self.buf[self.idx].parse::<T>().expect("parse error");
        self.idx += 1;
        return ret;
    }

    pub fn empty(&self) -> bool {
        return self.idx >= self.buf.len();
    }
}

fn main() {
    let mut sc = Scanner::new(&mut std::io::stdin());

    let n: usize = sc.read();
    let mut x = vec![0 as i64; n];
    let mut y = vec![0 as i64; n];

    for i in 0..n {
        let a: i64 = sc.read();
        let b: i64 = sc.read();
        x[i] = a + b;
        y[i] = a - b;
    }

    x.sort();
    y.sort();
    //println!("{:?}", x);
    //println!("{:?}", y);
    println!("{}", std::cmp::max(x[n - 1] - x[0], y[n - 1] - y[0]));
}


Measured memory_bytes: 27688
from sys import stdin

n = int(stdin.readline().rstrip())

c = [0]*n#次の駅までの時間
s = [0]*n#開通してからの時間
f = [0]*n#次の列車が来るまでの間隔

for i in range(1,n):
    c[i],s[i],f[i] = [int(x) for x in stdin.readline().rstrip().split()]

for j in range(n):
    time = 0
    for i in range(1+j,n):
        if time < s[i]:
            time = s[i]
        elif time%f[i] != 0:
            time += f[i]-time%f[i]
        time += c[i]
    print(time)

Measured memory_bytes: 3064
#include <bits/stdc++.h>
#define MOD 1000000007
typedef long long int ll;
using namespace std;

int main()
{
    string s; cin >> s;
    int ans = 0;
    int n = s.size();
    for(int i=0;i<(n+1)/2;i++){
        if(s[i] != s[n-1-i]) ans++;
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 256
#include<iostream>
using namespace std;
int x[4][2];double a, b;
int main() {
	while (cin >> a >> b) {
		a *= 10; b *= 10;
		if (a == 1) {
			x[3][0]++;
		}
		else if (a < 6) {
			x[2][0]++;
		}
		else if (a < 11) {
			x[1][0]++;
		}
		else {
			x[0][0]++;
		}
		if (b == 1) {
			x[3][1]++;
		}
		else if (b < 6) {
			x[2][1]++;
		}
		else if (b < 11) {
			x[1][1]++;
		}
		else {
			x[0][1]++;
		}
	}
	cout << x[0][0] << ' ' << x[0][1] << endl;
	cout << x[1][0] << ' ' << x[1][1] << endl;
	cout << x[2][0] << ' ' << x[2][1] << endl;
	cout << x[3][0] << ' ' << x[3][1] << endl;
	return 0;
}

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

int main() {
    while(1){
        int H, W;
        cin >> H >> W;
        if (H == 0 && W == 0){
            break;
        }
        for(int i = 0; i < H; i++){
            for(int i = 0; i < W; i++){
                cout << "#";
            }
            cout << endl;
        }
        cout << endl;
    }
}

Measured memory_bytes: 1152
import sys
N, M = list(map(int, input().split()))

ab = [[int(i) for i in input().split()] for i in range(N)]
cd = [[int(i) for i in input().split()] for i in range(M)]

# print("ab:", ab)
# print("cd:", cd)

for i, (a, b) in enumerate(ab):
    # print(i, " ", a, " ", b)
    min_dis = sys.maxsize
    min_idx = -1
    # print(min_idx, " ", min_dis)
    for j, (c, d)  in enumerate(cd):
        distance = abs(a-c) + abs(b-d)
        # print(j, " ", distance)
        if distance < min_dis:
            min_dis = distance
            min_idx = j
    print(min_idx+1)

Measured memory_bytes: 3064
#include <stdio.h>

int main(int argc, char *argv[])
{
	long long n,k,d,ans;
	scanf("%lld%lld%lld",&n,&k,&d);
	if(n<0)
		n=n*(-1);
	if(n/d<k){
		if(((n/d)%2)==(k%2))
			ans=n%d;
		else ans=(n%d)-d;
	}
	if(n/d>k)
		ans=n-k*d;
	if(ans<0)ans=ans*(-1);
	printf("%lld\n",ans);
}

Measured memory_bytes: 2144
import java.util.Scanner;
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Iterator;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while (true) {
			String str = sc.nextLine();
			if (str.equals(".")) break;
			boolean success = true;
			Deque<Character> stack = new ArrayDeque<>();
			for (int i = 0; i < str.length(); ++i) {
				char ch = str.charAt(i);
				if (ch == ')' || ch == ']') {
					if (!eliminate(ch, stack)) {
						success = false;
						break;
					}
				} else
					stack.push(ch);
			}
			if (stack.contains('(') || stack.contains('[')) {
				success = false;
			}
			System.out.println((success) ? "yes" : "no");
		}
	}
	public static boolean eliminate(char rparen, Deque<Character> stack) {
		char lparen = (rparen == ')') ? '(' : '[';
		char other = (lparen == '(') ? '[' : '(';
		int popcnt = 1;
		Iterator it = stack.iterator();
		while (it.hasNext()) {
			char ch = (char)it.next();
			if (ch == lparen) {
				for (int i = 0; i < popcnt; ++i) {
					char c = stack.remove();
					if (c == other) return false;
				}
				return true;
			}
			++popcnt;
		}
		return false;
	}
}


Measured memory_bytes: 47416
#include <bits/stdc++.h>
#include <array>
using namespace std;
using ULL = unsigned long long;
using UL = unsigned;
using LL = long long;
#define rep(i, n) for(UL i = 0; i < (n); i++)

struct Problem {

	void Solve() {
		ULL Q, H, S, D; cin >> Q >> H >> S >> D;
		UL N; cin >> N;
		S = min(S, min(Q * 4, H * 2));
		ULL ans = 0;
		if (N % 2) { N--; ans += S; }
		D = min(D, S * 2);
		ans += (N / 2) * D;
		cout << ans << endl;
	}


	Problem();
};
int main() {
	unique_ptr<Problem> p(new Problem());
	p->Solve();
	return 0;
}
Problem::Problem() {
	cout << fixed << setprecision(10);
}

Measured memory_bytes: 256
def factorize(n):
    # NOTE: if n == 1, return []
    if n < 1:
        raise Exception('Invalid input: n = {}'.format(n))
    i = 2
    ret = []
    while i * i <= n:
        while n % i == 0:
            n //= i
            ret.append(i)
        i += 1
    if n > 1:
        ret.append(n)
    return ret

N = int(input())
d = {}
for i in range(2, N+1):
    facts = factorize(i)
    for f in facts:
        if f not in d:
            d[f] = 1
        else:
            d[f] += 1
cnt = 1
for v in d.values():
    cnt = (cnt * (v+1)) % (10**9+7)
print(cnt)

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

typedef long long llong; 

int n,k;
llong T[MAX];

int check (llong p)
{
	int i=0;
	for (int j=0;j<k;j++)
	{
		llong s=0;
		while (s+T[i]<=p)
		{
			s+=T[i];
			i++;
			if (i==n) return n; 
			//这样可以试T[i]能不能装下，若不能，则I=4，说明最后一个货物 
			//没有被装下，若可以，则I=5，说明试过了最后一个且能装下。就是
			//检测i值，若i值等于5，则说明能装下T[4]，  
		}
	}
	return i;
}

int solve ()
{
	llong left=0;
	llong right = 100000*10000;
	llong mid=0;
	while (left<right)
	{
		mid=(left+right)/2;
		int v=check(mid);
		if (v>=n) right=mid;
		else left=mid+1; 
	}
	return right;
}

int main()
{
	cin>>n>>k;
	for (int i=0;i<n;i++) cin>>T[i];
	llong ans =solve();
	cout<<ans<<endl;
	return 0;
}



Measured memory_bytes: 3860
package main

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

var (
	uft []int
	ch  []int
)

func find(x int) int {
	if uft[x] == x {
		return x
	}

	uft[x] = find(uft[x])
	return uft[x]
}

func union(a, b int) {
	uft[a] = uft[b]
	ch[b] += ch[a]
}

func main() {
	var n, m int
	fmt.Scan(&n, &m)

	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	as := make([]int, m)
	bs := make([]int, m)
	for i := 0; i < m; i++ {
		sc.Scan()
		as[i], _ = strconv.Atoi(sc.Text())
		sc.Scan()
		bs[i], _ = strconv.Atoi(sc.Text())
	}

	uft = make([]int, n+1)
	ch = make([]int, n+1)
	for i := range uft {
		uft[i] = i
		ch[i]++
	}

	ans := make([]int64, m)
	ans[m-1] = int64(n * (n - 1) / 2)
	for i := m - 1; i >= 1; i-- {
		ar := find(as[i])
		br := find(bs[i])

		ans[i-1] = ans[i]
		if ar != br {
			ans[i-1] -= int64(ch[ar] * ch[br])
			union(ar, br)
			continue
		}
	}

	for _, v := range ans {
		fmt.Println(v)
	}
}


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

const int limit=16;
const int nmax=100010;

vector<int> graph[nmax];
int parent[nmax][limit]; // all is -1
int depth[nmax];

void dfs(int v,int p,int d){
	parent[v][0]=p;
	depth[v]=d;
	for(auto &v2:graph[v]) if(v2!=p) dfs(v2,v,d+1);
}

int lca(int u,int v){
	if(depth[u] < depth[v]) swap(u,v);
	for(int i=limit-1;i>=0;--i) if((depth[u]-depth[v])>>i&1) u=parent[u][i];
	if(u==v) return u;
	for(int i=limit-1;i>=0;--i){
		if(parent[u][i]!=parent[v][i]){
			u=parent[u][i];
			v=parent[v][i];
		}
	}
	return parent[u][0];
}

int main(void){
	int n; cin >> n;
	rep(i,n){
		int k; cin >> k;
		rep(j,k){
			int v; cin >> v;
			graph[i].push_back(v);
		}
	}

	// rep(i,n)rep(j,20) parent[i][j]=-1;
	dfs(0,-1,0);
	rep(i,n)rep(j,limit-1) parent[i][j+1]=parent[parent[i][j]][j];

	int q; cin >> q;
	rep(i,q){
		int u,v; cin >> u >> v;
		cout << lca(u,v) << endl;
	}
	return 0;
}

Measured memory_bytes: 17984
#include<bits/stdc++.h>
#define mod 1000000007
#define ll long long int
#define ar array
#define pb push_back
using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	int n,k;
	cin>>n>>k;
	int a[n];
	for(int i = 0; i<n; i++) cin>>a[i];
	ll ans = 0;
	for(int i = 00; i<n; i++)
	{
		ll t = min(abs(a[i]-k),a[i]);
		ans += 2*t;
	}
	cout<<ans<<endl;
	return 0;
}

Measured memory_bytes: 256
import itertools
n = int(input())
a = list(map(int,input().split()))
#'+-+-...'と'-+-+...'でそれぞれ求める
res1 = 0
res2 = 0
dif1 = 0
dif2 = 0
for i,j in enumerate(itertools.accumulate(a)):
    s = j + dif1
    t = j + dif2
    if i%2==0:
        if s<1:
            dif1 += 1 - s
            res1 += 1 - s
        if t>-1:
            dif2 -= 1 + t
            res2 += 1 + t
    else:
        if s>-1:
            dif1 -= 1 + s
            res1 += 1 + s
        if t<1:
            dif2 += 1 - t
            res2 += 1 - t
print(min(res1,res2))


Measured memory_bytes: 14212
#include<cstdio>
#include<cstring>
#include<algorithm>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define N 501000
#define db double
using namespace std;
int n,m,l;
db d[N][2];
int main()
{
	scanf("%d%d",&n,&l);
	db V=0,T=0;
	int he=0,ta=0;
	fo(i,1,n)
	{
		db x,y;scanf("%lf%lf",&x,&y);
		while(V+y>l)
		{
			db jy=min(d[he][1],V+y-l);
			d[he][1]-=jy;
			T-=jy*d[he][0];
			V-=jy;
			if(d[he][1]==0) he++;
		}
		V+=y;T+=x*y;
		for(d[++ta][0]=x,d[ta][1]=y;he<ta&&d[ta][0]<d[ta-1][0];ta--)
		{
			d[ta-1][0]=(d[ta-1][0]*d[ta-1][1]+d[ta][0]*d[ta][1])/(d[ta-1][1]+d[ta][1]);
			d[ta-1][1]+=d[ta][1];
		}
		printf("%lf\n",T/l);
	}
}

Measured memory_bytes: 16256