akhauriyash/Code-Regression huggingface dataset:
H, W = map(int, input().split())
mat = []
for _ in range(H):
    mat.append(list(map(int, input().split())))

ans = []
sw_rev = 0
for i in range(H):
    if sw_rev == 0:
        for j in range(W):
            if mat[i][j] % 2 != 0:
                if j == W-1:
                    if i == H-1:
                        continue
                    mat[i+1][j] += 1
                    ans.append((i, j, i+1, j))
                else:
                    mat[i][j+1] += 1
                    ans.append((i, j, i, j+1))
        sw_rev = 1
    else:
        for j in range(W)[::-1]:
            if mat[i][j] % 2 != 0:
                if j == 0:
                    if i == H-1:
                        continue
                    mat[i+1][j] += 1
                    ans.append((i, j, i+1, j))
                else:
                    mat[i][j-1] += 1
                    ans.append((i, j, i, j-1))
        sw_rev = 0
print(len(ans))
for x1, y1, x2, y2 in ans:
    print(x1+1, y1+1, x2+1, y2+1)

Measured memory_bytes: 24120
#include <stdio.h>
#include <ctype.h>
  
int main(void){
    char ch;
    int alfa[27] = {};
    int i;
    i=0;
    while(scanf("%c", &ch) != EOF){
        if(isupper(ch)){
            ch = tolower(ch);
        }
        i = ch - 'a';
        alfa[i] += 1;
    }
    for(i=0;i<26;i++){
        printf("%c : %d\n",i+'a',alfa[i]);
    }
    return(0);
}

Measured memory_bytes: 548
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <cmath>
#include <queue>
#include <deque>
#include <set>
#include <iomanip>
#include <utility>
#define ll long long
#define ld long double
using namespace std;

ll gcd(ll a, ll b){
	if(a%b>0) return gcd(b, a%b);
	return b;
}

int main() {
	int N;
	ll X, D;
	cin >> N >> X >> D;
	if(X==0){
		if(N==1 || D==0){
			cout << 1 << endl;
			return 0;
		}
		X += D;
		--N;
	}
	if(D==0){
		cout << N+1 << endl;
		return 0;
	}
	if(D<0){
		X *= -1;
		D *= -1;
	}
	map<ll, vector<pair<ll, ll>>> mp;
	ll sm=0, la=0;
	for(int i=0; i<=N; ++i){
		ll f=(D+(X*i)%D)%D;
		mp[f].push_back(make_pair((sm-f)/D, (la-f)/D));
		sm += X+D*i;
		la += X+D*(N-1-i);
	}
	ll ans=0;
	for(auto itr=mp.begin(); itr!=mp.end(); ++itr){
		vector<pair<ll, ll>> v=itr->second;
		sort(v.begin(), v.end());
		ll g=v[0].first, h=v[0].second;
		for(int i=1; i<v.size(); ++i){
			if(h<v[i].first){
				ans += h-g+1;
				g=v[i].first;
				h=v[i].second;
			}else{
				h=max(h, v[i].second);
			}
		}
		ans += h-g+1;
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 22144
N = int(input())
S = {}
for i in range(N):
    s = input()
    if s in S:
        S[s] += 1
    else:
        S[s] = 1
sorted_S = sorted(S.items(), key=lambda x: x[1], reverse=True)
a = []
count = -1
for s in sorted_S:
    if count == -1:
        a.append(s[0])
        count = s[1]
    elif count == s[1]:
        a.append(s[0])
    else:
        break
sorted_a = sorted(a)
for s in sorted_a:
    print(s)

Measured memory_bytes: 47324
n, m = map(int, input().split())

l = [0]*m
r = [0]*m

mi = 1
ma = n + 1

for i in range(m):
    l[i], r[i] = map(int, input().split())
    mi = max(mi, l[i])
    ma = min(ma, r[i])

ans = ma - mi + 1

if ans >= 0:
    print(ans)
else:
    print(0)


Measured memory_bytes: 10868
from bisect import bisect_left, bisect_right
from itertools import accumulate


def ge_m(x, m, n):
    total = 0
    for v in a:
        delta = x - v
        idx = bisect_left(a, delta)
        total += (n - idx)
    return total >= m


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

a.sort()
cum = [0] + list(accumulate(a))  # 累積和

# 1回の握手であがる幸福度のうち、最も低いものを求める
l = 0
r = a[-1] * 2 + 1
while r - l > 1:
    mid = (l + r) // 2
    if ge_m(mid, m, n):
        l = mid
    else:
        r = mid

# 最も低い幸福度よりも大きい値を足す
num = 0  # 握手の回数
ans = 0
for v in a:
    idx = bisect_right(a, l - v)
    num += n - idx
    ans += v * (n - idx) + (cum[-1] - cum[idx])
# 足りない握手の回数分、最も低い幸福度を足す
ans += (l * (m - num))
print(ans)

Measured memory_bytes: 14256
a = int(input())
b = int(input())
c = int(input())
x = int(input())

count = 0
for i in range(a+1):
  for j in range(b+1):
    for k in range(c+1):
      if 500*i + 100*j + 50*k == x:
        count += 1
print(count)

Measured memory_bytes: 3064
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>

using namespace std;

int main(){

    int K;
    string S;
    cin >> K >> S;
    if(K >= S.length()){
        cout << S << endl;
    }else{
        for(int i=0;i<K;i++)cout << S[i];
        cout << "..." << endl;
    }

    return 0;
}


Measured memory_bytes: 3628
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define FOR(i,s,n) for(int i = s; i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(n) (n).begin(), (n).end()
#define RALL(n) (n).rbegin(), (n).rend()
using ll = long long;
using ull = unsigned long long;

int main(void)
{
    IOS
    int a,b,c,d;
    cin >> a >> b >> c >>d;
    int ab = a * b;
    int cd = c * d;
    int ans = ab < cd ? cd : ab;
    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 256
#include <vector>
#include <iostream>
#include <cmath>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <fstream>
#include <unistd.h>
#include <string.h>
#include <string>
#include <numeric>
#include <queue>
#include <deque>
#include <sstream>
#include <iomanip>
#include <set>
#include <stack>
#include <cassert>
#include <functional>
#include <random>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vvl> vvvl;
typedef vector<vvvl> vvvvl;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<bool> vb;
typedef vector<vector<bool>> vvb;
typedef vector<vvb> vvvb;
typedef vector<vvvb> vvvvb;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef vector<vvs> vvvs;
typedef vector<char> vc;
typedef vector<vector<char>> vvc;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<vvd> vvvd;
typedef long double LD;
typedef vector<LD> vld;
typedef vector<pair<LD, LD>> vpld;
typedef pair<ll, ll> PL;
typedef vector<PL> vpl;
typedef vector<vector<PL>> vvpl;
typedef vector<vvpl> vvvpl;
typedef pair<ll, PL> TL;
typedef vector<TL> vtl;
typedef vector<vtl> vvtl;
typedef long double ld;
typedef vector<ld> vld;
const ll LINF = 1e17;
const double pi = 3.1415926535897932;
const string endstr = "\n";
#define FOR(i, a, b) for(ll i = (a); i < b; i++)
#define RFOR(i, a, b) for(ll i = (a); i > b; i--)
#define rep(i, n) for(ll i = 0; i < n; i++)
#define rrep(i, n) for(ll i = n-1; i > -1; i--)
#define FORMAP(it, m) for(auto it = m.begin(); it != m.end(); it++)
#define ff first
#define ss second
#define pb push_back
#define epb emplace_back
#define ALL(X) (X).begin(),(X).end()

template <typename T> T gcd(T a, T b) {return (a == 0) ? b : gcd(b%a, a);}
template <typename T> T lcm(T a, T b) { return a / gcd(a, b) * b;}

bool p_comp_fs(const PL p1, const PL p2){ return p1.first < p2.first;};
bool p_comp_fg(const PL p1, const PL p2){ return p1.first > p2.first;};
bool p_comp_ss(const PL p1, const PL p2){ return p1.second < p2.second;};
bool p_comp_sg(const PL p1, const PL p2){ return p1.second > p2.second;};
template <typename T>
vector<T> uniquen(vector<T> vec /* copy */){
    sort(ALL(vec)); vec.erase(unique(vec.begin(), vec.end()), vec.end()); return vec;
}

inline ll popcnt(ll x){return __builtin_popcountll((unsigned long long)x);};
template<class T> bool chmax(T &a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> bool chmin(T &a, T b) { if (a > b) { a = b; return true; } return false; }
//friend bool operator<(const tpl& lhs, const tpl& rhs){
//    return std::tie(lhs.l, lhs.r) < std::tie(rhs.l, rhs.r);
//}

bool bit(ll st, ll b){return ((st>>b)&1) == 1;}


int main(){
#ifdef __DEBUG_LOCAL__
    ifstream file("../../../../../in.txt"); if(file.is_open()) cin.rdbuf(file.rdbuf());
#endif
    ios_base::sync_with_stdio(false); cin.tie(nullptr);
    
    ll A, B, K; cin >> A >> B >> K;
    if(A > K){
        cout << A-K << " " << B << endstr;
    }
    else{
        cout << 0 << " " << max(B-(K-A), 0ll) << endstr;
    }    
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <vector>
#include <string>
#include <cstring>
using namespace std;
const int N = 1e5 + 5;
#define ll long long

int main(){
    int h,n,m;
    scanf("%d %d %d",&h,&n,&m);
    int mx = max(h,n);
    printf("%d\n",m%mx?m/mx+1:m/mx);
    return 0;
}


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

using namespace std;

int cnt[200 + 7];

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

    int k;
    cin >> k;
    for (int i = k; i >= 1; i--)
    {
        cnt[i] = (k / i) * (k / i) * (k / i);
        for (int j = 2 * i; j <= k; j += i)
        {
            cnt[i] -= cnt[j];
        }
    }
    int ans = 0;
    for (int i = 1; i <= k; i++)
    {
        ans += i * cnt[i];
    }
    cout << ans << "\n";
}


Measured memory_bytes: 3616
#include <iostream>
#include <vector>
#include <numeric>//accumulate(v.begin(), v.end(), 0);
#include <algorithm>//sort(v.begin(),v.end());
#include <string>//
#include <cmath>
#include <iomanip> //setprecision(2)
using namespace std;
#define ll long long
#define rep(i, n) for(int i = 0; i < (int)(n); i++)

int main(){
        int N;
        int a,b;
        cin >> N;
        if(N==1) {
                cout << "Hello World"<<endl;
        }else{
                cin >> a >> b;
                cout <<a+b<<endl;
        }


        return 0;
}


Measured memory_bytes: 256
#include <stdio.h>

int main(void)
{
	int i;
	int j;
	int n;
	int m;
	int question[101] = {0};
	int maxPos;
	int index;
	
	while( 1 )
	{
		scanf( "%d%d", &n, &m );
		if( n == 0 && m == 0 )break;
		
		for( i = 0; i < n; i++ )
		{
			for( j = 0; j < m; j++ )
			{
				int buf;
				scanf( "%d", &buf );
				if( buf == 1 )
				{
					question[j]++;
				}
			}
		}
		
		for( i = 0; i < m; i++ )
		{
			maxPos = 0;
			index = 0;
			for( j = 0; j < m; j++ )
			{
				if( maxPos < question[j] )
				{
					maxPos = question[j];
					index = j;
				}
			}
			printf( "%s%d", i == 0 ? "" : " ", index + 1 );
			question[index] = 0;
		}
		
		puts("");
	}
	
	return (0);
}

Measured memory_bytes: 612
import sys
input = sys.stdin.readline
def main():
  n=int(input())
  a=list(map(int,input().split()))
  mod=pow(10,9)+7
  ans=0
  bit=[0]*61 #bit[i]:2^iの位が1である物の個数
  for ai in a:
    for j in range(61):
      if ((ai>>j) & 1):
        bit[j]+=1
  for i in range(61):
    ans+=(pow(2,i)%mod)*bit[i]*(n-bit[i])
    ans%=mod
  print(ans)
if __name__=='__main__':
  main()


Measured memory_bytes: 123132
n, k = gets.split.map &:to_i
trees = []

n.times do
  trees << gets.to_i
end

trees.sort!
ans = 1E9 + 10

for i in 0 .. n - k
  min = trees[i + k - 1] - trees[i]
  ans = [min, ans].min
end

puts ans


Measured memory_bytes: 4016
#include <bits/stdc++.h>
using namespace std;
const int mod = 1000000007;
int h, l, clk, ans, p[1 << 17], a[1 << 18], tag[1 << 18];
void go(int u, int prd) {
	while (u > 1) {
		prd = 1ll * prd * u % mod;
		if (tag[u] != clk) { a[u] = 0; tag[u] = clk; }
		a[u] = (a[u] + prd) % mod;
		u >>= 1;
	}
}
void clc(int u, int prd) {
	while (u > 1) {
		prd = 1ll * prd * u % mod;
		int fa = u >> 1;
		int v = u ^ 1;
		if (tag[v] == clk) {
			ans = (ans + 1ll * prd * a[v] % mod * fa) % mod;
		}
		u >>= 1;
	}
}
void dfs2(int u, int prd) {
	if (u >= l) {
		go(p[u - l] + l, prd);
		return;
	}
	dfs2(u << 1, 1ll * prd * (u << 1) % mod);
	dfs2(u << 1 | 1, 1ll * prd * (u << 1 | 1) % mod);
}
void dfs3(int u, int prd) {
	if (u >= l) {
		clc(p[u - l] + l, prd);
		return;
	}
	dfs3(u << 1, 1ll * prd * (u << 1) % mod);
	dfs3(u << 1 | 1, 1ll * prd * (u << 1 | 1) % mod);
}
void gao(int u) {
	clk++;
	dfs2(u << 1, u << 1);
	dfs3(u << 1 | 1, 1ll * u * (u << 1 | 1) % mod);
}
void dfs(int u) {
	if (u >= l) return;
	gao(u);
	dfs(u << 1);
	dfs(u << 1 | 1);
}
int main() {
	scanf("%d", &h);
	l = 1 << (h - 1);
	for (int i = 0; i < l; i++) {
		scanf("%d", &p[i]);
		p[i]--;
	}
	dfs(1);
	printf("%d\n", ans);
	return 0;
}

Measured memory_bytes: 6336
#pragma GCC optimize(2)
#include <cstdio>
#include <cstring>
using namespace std;

char a[110000],b[110000];

int main()
{
	scanf("%s",a+1);
	int l=strlen(a+1);
	for(int i=1,j=l;i<=l,j>=1;++i,--j) b[i]=a[j];
	for(int i=1;i<=l;++i) {
		if(b[i]=='b') b[i]='d';
        else if(b[i]=='d') b[i]='b';
        else if(b[i]=='p') b[i]='q';
        else if(b[i]=='q') b[i]='p';
	}
	for(int i=1;i<=l;++i)
		if(a[i]!=b[i]) { printf("No\n"); return 0; }
	printf("Yes\n");
	return 0;
}

Measured memory_bytes: 384
#include <bits/stdc++.h>
#define pi acos(-1)
#define maxn 200001
using namespace std;
typedef long long ll;
const int mx=100005;
//void init(int node, int b, int e)
//{
//    if (b == e) {
//        tree[node] = a[b];
//        return;
//    }
//    int Left = node * 2;
//    int Right = node * 2 + 1;
//    int mid = (b + e) / 2;
//    init(Left, b, mid);
//    init(Right, mid + 1, e);
//    tree[node] = __gcd(tree[Left],tree[Right]);
//}
//int query(int node, int b, int e, int i, int j)
//{
//    if (i > e || j < b)
//        return 0;
//    if (b >= i && e <= j)
//        return tree[node];
//    int Left = node * 2;
//    int Right = node * 2 + 1;
//    int mid = (b + e) / 2;
//    int p1 = query(Left, b, mid, i, j);
//    int p2 = query(Right, mid + 1, e, i, j);
//    return __gcd(p1,p2);
//}
//void update(int node, int b, int e, int i, int newvalue)
//{
//    if (i > e || i < b)
//        return;
//    if (b >= i && e <= i) {
//        tree[node] = newvalue;
//        return;
//    }
//    int Left = node * 2;
//    int Right = node * 2 + 1;
//    int mid = (b + e) / 2;
//    update(Left, b, mid, i, newvalue);
//    update(Right, mid + 1, e, i, newvalue);
//    tree[node] = __gcd(tree[Left] , tree[Right]);
//}

int main(){

    int re,mi,m;
    cin>>re>>mi>>m;
    vector<int>r;
    vector<int>mm;
    for(int i=0;i<re;i++){
        int x;
        cin>>x;r.push_back(x);
    }
    for(int i=0;i<mi;i++){
        int x;
        cin>>x;
        mm.push_back(x);
    }
    vector<int>ans;
    for(int i=0;i<m;i++){
        int x,y,c;
        cin>>x>>y>>c;
   		ll so=r[x-1]+mm[y-1]-c;
        ans.push_back(so);
    }
    sort(r.begin(),r.end());
    sort(mm.begin(),mm.end());
    int x=r[0]+mm[0];
    //for(auto x: ans)cout<<x<<" ";
    //cout<<endl;
    for(auto y: ans){
        if(x>=y){
          x=y;
        }
    }
    cout<<x<<endl;
}


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





int main(){
	int N,M;
	cin>>N>>M;
	vector<pair<int,int>> A(N);
	for(int i=0;i<N;i++){
		cin>>A[i].first>>A[i].second;
	}
	sort(A.begin(),A.end());
	
	long long ans = 0;
	
	for(int i=0;i<N;i++){
		ans = (long long)ans+(long long)min(M,A[i].second)*A[i].first;
		M -= min(M,A[i].second);
		if(M==0)break;
	}
	
	cout<<ans<<endl;
			
	
	return 0;
}

Measured memory_bytes: 1024
n = gets.to_i
as = gets.split.map(&:to_i)
bs = gets.split.map(&:to_i)

yoryoku = 0
defed = 0

n.times do |i|
  d1 = [yoryoku, as[i]].min
  nokori = as[i] - d1
  d2 = [bs[i], nokori].min
  yoryoku = bs[i] - d2

  defed += d1 + d2
end

# n-th town
d1 = [yoryoku, as[n]].min

defed += d1

p defed


Measured memory_bytes: 19656
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define elif else if
#define sp(x) fixed << setprecision(x)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const ll MOD = 1e9+7;
//const ll MOD = 998244353;
const int inf = (1<<30)-1;
const ll INF = (1LL<<60)-1;
const ld EPS = 1e-10;
template<typename T> bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;};
template<typename T> bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;};

int main(){
    int N;
    cin >> N;
    char ans[2*N];
    int l1 = 1, l2 = N+1;
    string res[2*N+1];
    cout << "? ";
    rep2(i, 1, N) cout << i << ' '; cout << endl;
    cin >> res[1];
    cout << "? ";
    rep2(i, N+1, 2*N) cout << i << ' '; cout << endl;
    cin >> res[N+1];
    while(l2-l1 > 1){
        int n = (l1+l2)/2;
        cout << "? ";
        rep2(i, n, n+N-1) cout << i << ' '; cout << endl;
        cin >> res[n];
        if(res[n] != res[l1]) l2 = n;
        else l1 = n;
    }
    int l = l2, r = l1+N-1;
    string x;
    rep2(i, 1, 2*N){
        if(l <= i && i <= r) continue;
        cout << "? ";
        rep2(j, l, r) cout << j << ' ';
        cout << i << endl;
        cin >> x;
        if(x == "Red") ans[i] = 'R';
        else ans[i] = 'B';
    }
    rep2(i, l, r){
        cout << "? ";
        rep2(j, 1, l-2) cout << j << ' ';
        rep2(j, r+2, 2*N) cout << j << ' ';
        cout << i << endl;
        cin >> x;
        if(x == "Red") ans[i] = 'R';
        else ans[i] = 'B';
    }
    cout << "! ";
    rep2(i, 1, 2*N) cout << ans[i]; cout << endl;
}

Measured memory_bytes: 724
#include <iostream>

int main()
{
    int S;
    std::cin >> S;
    
    int upper, lower;
    
    upper = static_cast<int>(S / 100);
    lower = static_cast<int>(S % 100);
    
    auto checkMonth = [&](int num) -> bool {
        return (1 <= num) && (num <= 12);
    };
    
    bool isUpperMonth = checkMonth(upper);
    bool isLowerMonth = checkMonth(lower);
    
    if (!isUpperMonth && !isLowerMonth) { 
        std::cout << "NA" << std::endl;
    } else if (!isUpperMonth) {
        std::cout << "YYMM" << std::endl;
    } else if (!isLowerMonth) {
        std::cout << "MMYY" << std::endl;
    } else {
        std::cout << "AMBIGUOUS" << std::endl;
    }
    
    return 0;
}

Measured memory_bytes: 256
#include<stdio.h>
int main(){
  char a[100],b[100],T,c[100];
  int i,j,k,I=0,J=0,count=0,t=0;
  


    while(1){
      scanf("%c",&a[I]);
      if(a[I]=='\n') break;
      I++;
    }

   while(1){
      scanf("%c",&b[J]);
      if(b[J]=='\n') break;
      J++;
    }

   while(count!=J){
     
     count=0;
   for(i=0;i<J;i++){
     if(a[i]==b[i]) count++;
     else count--;
   }
  
   if(count!=J){
     for(i=0;i<I;i++){
       if(i==0) T=a[0];
         a[i]=a[i+1];
	 if(i==I-1)  a[I-1]=T;
     }
     
     t++;
     if(t==100) break;
     
   }
   }
   if(count==J) printf("Yes\n");
   else printf("No\n");
   

   return 0;
}

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

using namespace std ;

const long long INF = 1e18 ;
const int MAX = 1e5 + 10 ;

int arr[MAX] ;
int n ;

int main()
{
	ios_base::sync_with_stdio(0) ;
	cin.tie(0) ;
	cin>>n ;
	long long ans = 1ll ;
	bool flag = false ;
	for(int i = 0 ; i < n ; ++i)
	{
		long long x ;
		cin>>x ;
		if(x == 0)
			flag = true ;
		if(ans == -1)
			continue ;
		if(INF / ans < x)
			ans = -1 ;
		else
			ans *= x ;
		if(ans > INF)
			ans = -1 ;
	}
	if(flag)
		ans = 0 ;
	return cout<<ans<<"\n" , 0 ;
}		

Measured memory_bytes: 3656
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <cmath>
#define ill long long
#define rep(i, a, b) for(ill i = (ill)(a); i < (ill)(b); i++)
#define fcout cout << fixed << setprecision(10)
using namespace std;

int main() {
  int n, l;
  cin >> n >> l;
  int sum = 0, mn = 10000;
  rep(i, 0, n) {
    sum += l+i;
    if(abs(l+i) < abs(mn)) mn = l+i;
  }
  cout << sum - mn << "\n";
  //cout << sum << " " << mn;
}

Measured memory_bytes: 3628
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <map>
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <random>
#include <stack>
#include <set>
#include <unordered_set>

#define bug(x) cout<<"zdongdebug1: "<<x<<endl;
#define bug2(x, y) cout<<"zdongdebug2: "<<x<<" "<<y<<endl;
#define bug3(x, y, z) cout<<"zdongdebug3: "<<x<<" "<<y<<" "<<z<<endl;
using namespace std;
typedef long long ll;
const int maxn = 5005;
const int mod = 1000000007;

int n,m;
int p[maxn];
ll v[maxn];
ll s[maxn];
int len[maxn];
int c[maxn];

int main() {
#ifdef suiyuan2009
  freopen("/Users/suiyuan2009/CLionProjects/icpc/input.txt", "r", stdin);
  //freopen("/Users/suiyuan2009/CLionProjects/icpc/output.txt", "w", stdout);
#endif
  cin>>n>>m;
  for(int i=1;i<=n;i++)cin>>p[i];
  for(int i=1;i<=n;i++)cin>>v[i];
  for(int i=1;i<=n;i++){
    if(c[i])continue;
    int cur = i;
    ll sum = 0;
    int cnt = 0;
    while(!c[cur]){
      c[cur] = i;
      sum += v[cur];
      cur = p[cur];
      cnt++;
    }
    //bug3(i, sum, cnt)
    s[i] = sum;
    len[i] = cnt;
  }
  ll ret = -1000000000L * 1000000000L;
  for(int i=1;i<=n;i++){
    int fa = c[i];
    int tt = m/len[fa];
    int lft = m % len[fa];
    if(tt>0){
      lft += len[fa];
      tt--;
    }
    ll ans = v[i];
    ll mx = -1000000000L * 1000000000L;
    ll sum = 0;
    int cur = i;
    while(lft--){
      sum += v[cur];
      cur = p[cur];
      mx = max(sum, mx);
    }
    ans = max(ans, mx);
    if(s[fa]>0&&tt){
      ans = max(ans, tt * s[fa] + max(0LL, mx));
    }
    ret=max(ret, ans);
  }
  cout<<ret<<endl;
  return 0;
}

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

struct Team{
  int team_num,time,correct;
};

int main(){
  Team data[51];
  while(1){
    int i,j,T,P,R; cin >> T >> P >> R;
    if ( T == 0 && P == 0 && R == 0 ) break;
    for( i = 1; i <= T; i++ ){
      data[i].time = 0;
      data[i].correct = 0;
      data[i].team_num = i;
    }

    int t,p,jikan,twrong[51][11];
    for( i = 0; i < 51; i++ ){
      for( j = 0; j < 11; j++ ){
	twrong[i][j]=0;
      }
    }
    string str;
    for( i = 0; i < R; i++ ){
      cin >> t >> p >> jikan >> str;
      if( str == "CORRECT" ){
	data[t].correct++;
	data[t].time = data[t].time + twrong[t][p] * 1200 + jikan;
      }else if( str == "WRONG" ){
	twrong[t][p]++;
      }
    }
    for( i = 0; i < T; i++ ){
      for( j = 1; j < T; j++ ){
	if( data[j].team_num > data[j+1].team_num ) 
	  swap( data[j],data[j+1] );
      }
    }

    for( i = 0; i < T; i++ ){
      for( j = 1; j < T; j++ ){
	if( data[j].time > data[j+1].time ) 
	  swap( data[j],data[j+1] );
      }
    }

    for( i = 0; i < T; i++ ){
      for( j = 1; j < T; j++ ){
	if( data[j].correct < data[j+1].correct ) 
	  swap( data[j],data[j+1] );
      }
    }

    for( i = 1; i <= T; i++ ){
      cout << data[i].team_num << " "
	   << data[i].correct << " " << data[i].time << endl;
    }
    
  }
  return 0;
}

Measured memory_bytes: 1216
def gcd(a, b):
	while b:
		a, b = b, a % b
	return a

def lcm(a, b):
  return a * b // gcd (a, b)

n=int(input())
t=[]
for i in range(n):
 t.append(int(input()))
c=t[0]
for i in range(1,n):
 c=lcm(c,t[i])
print(c)

Measured memory_bytes: 3060
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <cmath>
#include <iomanip>
#include <stack>
#include <queue>
#include <numeric>
#include <map>
#include <unordered_map>
#include <set>
#include <fstream>
#include <chrono>
#include <random>
#include <bitset>
#define rep(i,n) for(int i=0;i<(n);i++)
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define sz(x) ((int)(x).size())
#define pb push_back
#define mod 1000000007
using ll = long long;
using namespace std;

ll inv(ll x) {
    ll res = 1;
    ll k = mod - 2; // x^kがxの逆元
    while (k) {	// 二分累乗法
        if (k & 1) res = (res * x) % mod;
        x = (x * x) % mod;
        k >>= 1;
    }
    return res;
}

int main(){
  ll N; cin >> N;
  vector<ll> X(N); rep(i,N) cin >> X[i];
  vector<ll> kaijo(100100, 1);
  rep(i,100005){
    kaijo[i+2] = kaijo[i+1] * (i+2);
    kaijo[i+2] %= mod;
  }
  ll ans = 0;
  ll now = kaijo[N-1];
  for(ll i=0; i<N-1; i++){
    ans += now*(X[i+1]-X[i]);
    ans %= mod;
    now += kaijo[N-1]*inv(i+2);
    now %= mod;
  }
  cout << ans%mod << endl;
  return 0;
}


Measured memory_bytes: 1792
#include <iostream>
#include <regex>
#include <iostream>
#include <regex>
#include <locale>
#include <cmath>
using namespace std;
 
int main() {
  int n, a;
  cin >> n;
  for(int i = 0; i < n; i++) {
    cin >> a;
    if(a % 2 == 0) {
      if(a % 3 != 0 && a % 5 != 0) {
        cout << "DENIED";
        return 0;
      }
    }
  }
  cout << "APPROVED";
  return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define r(i,n) for(int i=0;i<n;i++)
using namespace std;
#define EPS (1e-8)
#define equals(a,b) (fabs((a)-(b))<EPS)
class Point{
  public:
  double x,y;
  Point(double x=0,double y=0):x(x),y(y){}
  Point operator + (Point p){return Point(x+p.x,y+p.y);}
  Point operator - (Point p){return Point(x-p.x,y-p.y);}
};
struct seg{Point p1,p2;};
double norm(Point p){return p.x*p.x+p.y*p.y;}
double abs(Point p){return sqrt(norm(p));}
double dot(Point a,Point b){return a.x*b.x+a.y*b.y;}
double cross(Point a,Point b){return a.x*b.y-a.y*b.x;}
double getDistancePP(Point a,Point b){return abs(a-b);}
double getDistanceLP(seg l,Point p){return abs(cross(l.p2-l.p1,p-l.p1)/abs(l.p2-l.p1));}
double getDistanceSP(seg s,Point p){
  if(dot(s.p2-s.p1,p-s.p1)<0.0)return abs(p-s.p1);
  if(dot(s.p1-s.p2,p-s.p2)<0.0)return abs(p-s.p2);
  return getDistanceLP(s,p);
}
int n,m,c=1,pre,fro,p,t;
Point a[5001];
seg w;
bool vis[5001];double d[5001];
double dd=1000000000,dis=0;
int main(){
  cin>>n>>m;n++;
  r(i,n)cin>>a[i].x>>a[i].y;
  r(i,n)d[i]=abs(a[0]-a[i]);
  vis[0]=1;
  seg w;w.p1=a[0];w.p2=a[p];
  while(m--){
    dd=10000000;t=-1;c=0;
    r(i,n)if(!vis[i])if(t<0||d[i]<d[t])t=i;
    r(i,n)if(vis[i])if(abs(a[i]-a[t])<abs(a[c]-a[t]))c=i;
    dis+=abs(a[c]-a[t]);
    w.p1=a[c];w.p2=a[t];
    vis[t]=1;
    r(i,n)if(!vis[i])d[i]=min(d[i],getDistanceSP(w,a[i]));
  }
  printf("%.12f\n",dis);
  return 0;
}

Measured memory_bytes: 3404
import java.util.Scanner;

public class Main{

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);

	    int a = sc.nextInt();
	    int b = sc.nextInt();
	    int h = sc.nextInt();

	    int ans = (a+b)*h/2;
	    System.out.println(ans);
	}
}

Measured memory_bytes: 9428
#include "bits/stdc++.h"
#define rep(i,n) for(int i = 0; i < (n); ++i)
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int n;
    string s;
    cin >> n >> s;
    int ans = 0;
    rep(i,n-1){
        int cnt = 0;
        set<char> t, u;
        rep(j,i){
            t.insert(s[j]);
        }
        for(int j = i; j < n; j++){
            u.insert(s[j]);
        }
        for(auto p : t){
            for(auto q : u){
                if(p == q) cnt++;
            }
        }
        chmax(ans, cnt);
    }
    cout << ans << endl;
    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);
		boolean reverseEven = true;
		StringBuilder top = new StringBuilder("");
		StringBuilder bottom = new StringBuilder("");
		String s = sc.next();
		int q = sc.nextInt();
		for(int i = 0; i < q; i++){
			int q1 = sc.nextInt();
			if(q1 == 1){
				reverseEven = !reverseEven;
			}else{
				int f = sc.nextInt();
				if(f == 1){
					if(reverseEven){
						top.insert(0, sc.next());
					}else{
						bottom.append(sc.next());
					}
				}else{
					if(reverseEven){
						bottom.append(sc.next());
					}else{
						top.insert(0, sc.next());
					}
				}
			}
		}
		StringBuilder ans = top.append(s).append(bottom);
		if(! reverseEven){
			ans = ans.reverse();
		}
		System.out.println(ans);
	}
}


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

typedef unsigned long long ll;
typedef std::pair<int, int> P;

#define For(i, a, b) for(int i = (a); i < (b); i++)
#define Rep(i, n) For(i, 0, (n))
#define Rrep(i, n) for(int i = (n - 1); i >= 0; i--)
#define All(i, x) for(typeof(x.begin()) i = x.begin(); i != x.end(); i++)
#define ReAll(i, x) for(typeof(x.end()) i = x.end(); i != x.begin(); i--)
#define pb push_back

const int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const int MAX = 100000;
const int INF = 1e9;
const int MOD = 1000000007;

void solve(){
	int n; cin >> n;
	vector<int> a, b;
	Rep(i, n){
		int tmp; cin >> tmp;
		if(i % 2 == 0){
			a.pb(tmp);
		}else{
			b.pb(tmp);
		}
	}
	map<int, int> ma, mb;
	All(i, a) ma[*i] += 1;
	All(i, b) mb[*i] += 1;
	P A[2] = {P(0, 0), P(0, 0)}, B[2] = {P(0, 0), P(0, 0)};
	int count = 0;
	All(i, ma){
		if(count == 0){
			A[0] = P(i->first, i->second);
			count += 1;
		}else if(count == 1){
			if(i -> second > A[0].second){
				A[1].first = A[0].first;
				A[1].second = A[0].second;
				A[0] = P(i->first, i->second);
			}else{
				A[1] = P(i->first, i->second);
			}
			count += 1;
		}else{
			if(i -> second > A[0].second){
				A[1].first = A[0].first;
				A[1].second = A[0].second;
				A[0] = P(i->first, i->second);
			}else if(i -> second > A[1].second){
				A[1] = P(i->first, i->second);
			}
		}
	}
	count = 0;
	All(i, mb){
		if(count == 0){
			B[0] = P(i->first, i->second);
			count += 1;
		}else if(count == 1){
			if(i -> second > B[0].second){
				B[1].first = B[0].first;
				B[1].second = B[0].second;
				B[0] = P(i->first, i->second);
			}else{
				B[1] = P(i->first, i->second);
			}
			count += 1;
		}else{
			if(i -> second > B[0].second){
				B[1].first = B[0].first;
				B[1].second = B[0].second;
				B[0] = P(i->first, i->second);
			}else if(i -> second > B[1].second){
				B[1] = P(i->first, i->second);
			}
		}
	}
	if(A[0].first == B[0].first){
		cout << min(n - A[0].second - B[1].second, n - A[1].second - B[0].second) << endl;
	}else{
		cout << n - A[0].second - B[0].second << endl;
	}
}

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


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

typedef double D;
struct P {
  D x, y;
  P(D x_, D y_) : x(x_), y(y_) { }
};

D outp(P a, P b) {
  return a.x*b.y - a.y*b.x;
}

int main() {
  int n = 1;
  while(true) {
    int N; cin >> N;
    if(N == 0) break;
    vector<P> ps;
    for(int i = 0; i < N; ++i) {
      D x, y;
      cin >> x >> y;
      ps.emplace_back(x, y);
    }
    D res = 0.0;
    for(int i = 0; i < N; ++i) {
      res -= outp(ps[i], ps[(i+1)%ps.size()]);
    }
    res /= 2.0;
    cout.setf(ios::fixed);
    cout.precision(1);
    cout << n << ' ' << res << endl;
    ++n;
  }
}

Measured memory_bytes: 1296
N,M = list(map(int,input().split()))
p = 10**9+7

F = [1] * (5*10**5+1)
for i in range(1,5*10**5+1):
    F[i] = (F[i-1]*i)%p

MAXN = 5*(10**5)+10
MOD = p
f = [1]
for i in range(MAXN):
    f.append(f[-1] * (i+1) % MOD)
def nCr(n, r, mod=MOD):
    return f[n] * pow(f[r], mod-2, mod) * pow(f[n-r], mod-2, mod) % mod

out = 0
for K in range(N+1):
    A = nCr(M,K,p)*F[K]
    B = nCr(M-K,N-K,p)*F[N-K]
    C = (-1)**K
    out = (out + nCr(N,K,p)*A*B*B*C)%p
print(out)

Measured memory_bytes: 108164
#include <iostream>
#include <vector>
#include <deque>
#include <cmath>
#include <map>
#include <set>
#include <unordered_set>
#include <algorithm>
#include "iomanip"
#include <cstdio>
#include <cstring>

using namespace std;


int main() {
    int a;
    cin >> a;
    cout << "ABC" << a;

}

Measured memory_bytes: 256
#![allow(unused, non_snake_case, dead_code, non_upper_case_globals)]
#![macro_use]

use std::cmp::*;
use std::collections::*;
use std::io::*;
use std::mem::*;
use std::num::*;
use std::slice::*;

fn main() {
    let (r, w, e) = (stdin(), stdout(), stderr());
    let mut io = IO::new(r.lock(), w.lock(), e.lock());
    // =============================================== //

    let n: usize = io.read();
    let a = io.readn::<i64>(n);

    let mut dp = vec![vec![0i64; 3030]; 3030];

    // [l,r)
    for width in 1..n + 1 {
        for l in 0..n - width + 1 {
            let r = l + width;
            if width % 2 == n % 2 {
                dp[l][r] = max(dp[l + 1][r] + a[l], dp[l][r - 1] + a[r - 1]);
            } else {
                dp[l][r] = min(dp[l + 1][r] - a[l], dp[l][r - 1] - a[r - 1]);
            }
        }
    }
    io.writeln(dp[0][n]);
}

// IO
struct IO<R: Read, W: Write, E: Write> {
    Read: R,
    Write: BufWriter<W>,
    Error: BufWriter<E>,
}
impl<R: Read, W: Write, E: Write> IO<R, W, E> {
    fn new(r: R, w: W, e: E) -> IO<R, W, E> {
        IO {
            Read: r,
            Write: BufWriter::new(w),
            Error: BufWriter::new(e),
        }
    }
    fn read<T>(&mut self) -> T
    where
        T: std::str::FromStr,
    {
        let next: String = self
            .Read
            .by_ref()
            .bytes()
            .map(|c| c.unwrap() as char)
            .skip_while(|c| c.is_whitespace())
            .take_while(|c| !c.is_whitespace())
            .collect();
        next.parse().ok().unwrap()
    }
    fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    fn readn<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read::<T>()).collect::<Vec<_>>()
    }
    fn readmat<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n).map(|_| self.readn(m)).collect()
    }
    fn write<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
    }
    fn writeln<S: ToString>(&mut self, val: S) {
        self.Write.write(val.to_string().as_bytes());
        self.Write.write(b"\n");
    }
    fn debug<S: std::fmt::Debug>(&mut self, val: S) {
        writeln!(self.Error, "(debug ) {:?}", &val);
    }
    fn debug2<S: std::fmt::Debug, T: std::fmt::Debug>(&mut self, val1: S, val2: T) {
        writeln!(self.Error, "(debug2) {:?} -> {:?}", val1, val2);
    }
}


Measured memory_bytes: 90364
import heapq
n,m = map(int,input().split())
a = list(map(lambda x: int(x)*(-1), input().split()))
heapq.heapify(a)
for i in range(m):
  min = heapq.heappop(a)
  heapq.heappush(a, (-min//2)*(-1))
print(-sum(a))

Measured memory_bytes: 14252
#define _CRT_SECURE_NO_WARNINGS
#include "bits/stdc++.h"
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define FOR(i, m, n) for(int i=(m); i<(n); ++i)
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mp make_pair
#define pb push_back
#define Cout(x) cout << (x) << endl
#define Cout2(x, y) cout << (x) << " " << (y) << endl
#define dump(x) cerr << #x << " = " << (x) << endl;
typedef long long LL;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<string> VS;
typedef vector<bool> VB;
typedef vector<vector<int>> VVI;
typedef pair<int, int> PII;
const int inf = (int)1e9;
const double pi = acos(-1.0);
template <class A>ostream & operator<<(ostream & o, const vector<A> & p) { o << "{"; for (int i = 0; i < (int)p.size(); ++i)o << (i > 0 ? ", " : "") << p[i]; o << "}"; return o; }
template <class A, class B>ostream & operator<<(ostream & o, const pair<A, B> & p) { o << "{" << p.first << ", " << p.second << "}"; return o; }
template <class A, class B>ostream& operator<<(ostream & o, const map<A, B> & p) { o << "{"; for (auto it = p.begin(); it != p.end(); ++it) o << (it != p.begin() ? ", " : "") << *it; o << "}"; return o; }
template <class A>ostream & operator<<(ostream & o, const set<A> & p) { o << "{"; for (auto it = p.begin(); it != p.end(); ++it) o << (it != p.begin() ? ", " : "") << *it; o << "}"; return o; }
void print() { cerr << endl; }
template <class H> void print(H && h) { cerr << h << endl; }
template <class H, class... T> void print(H && h, T && ... t) { cerr << h << " "; print(forward<T>(t)...); }

string gyaku(string s) {
	reverse(all(s));
	for (auto& c : s) {
		switch (c) {
		case 'b':
			c = 'd'; break;
		case 'd':
			c = 'b'; break;
		case 'p':
			c = 'q'; break;
		case 'q':
			c = 'p'; break;
		}
	}
	return s;
}

int main() {
	string s; cin >> s;
	puts(s == gyaku(s) ? "Yes" : "No");
	print(s, gyaku(s));
}

Measured memory_bytes: 512
#include<cstdio>

int main(){
    int H,W;
    for(int c = 1;; c++){
        scanf("%d %d",&H,&W);
        if(H == 0 && W == 0){
            break;
        }else if(H != 0 && W != 0){
            for(int i = 1; i <= H; i++){ //高さ1からHまで
                if(i == 1){ //高さ1の行
                    for(int j = 1; j <= W; j++){
                        if(j < W){
                            printf("#");
                        }
                        else{
                            printf("#\n");
                        }
                    }
                }
                else if(2 <= i && i <= H - 1){ //高さ2~H-1の行
                    for(int k = 1; k <= W; k++){
                        if(k == 1){
                            printf("#");
                        }else if(2 <=k && k <= W - 1){
                            printf(".");
                        }
                        else{
                            printf("#\n");
                        }
                    }
                }
                else{ //高さHの行
                    for(int l = 1; l <= W; l++){
                        if(l < W){
                            printf("#");
                        }
                        else{
                        printf("#\n\n");
                        }
                    }
                }
            }
        }
    }
    return 0;
}


Measured memory_bytes: 2672
n = int(input())
a = list(map(int, input().split()))
rods = []
tmp = {}
for i in a:
    if i in tmp:
        tmp[i] += 1
        if tmp[i] >= 2:
            rods.append(i)
            tmp[i] = 0
    else:
        tmp[i] = 1

rods.sort(reverse=True)
if len(rods) >= 2:
    print(rods[0] * rods[1])
else:
    print(0)

Measured memory_bytes: 22068
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;

int main()
{
	long long a,b,k;
	scanf("%lld %lld %lld",&a,&b,&k);
	//printf("%lld %lld %lld\n",a,b,k);
	if(a>=k){
		a-=k;
		//cout<<a<<" "<<b<<endl;
		printf("%lld %lld\n",a,b);
	}
	else{
		//cout<<a<<b<<k;
		k=k-a;
		a=0;
		//cout<<k<<' '<<b<<endl; 
		b=(b-k)>=0?b-k:0;
		printf("%lld %lld\n",a,b);
	}
	
	
	return 0;
} 

Measured memory_bytes: 256
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<bits/stdc++.h>
using namespace std;
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/tree_policy.hpp>
//using namespace __gnu_pbds;
/*---------------------DEBUGGING--------------------------------------------*/
void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif
/*-------------------------------------------------------------------------------------*/
//#define mp make_pair
#define pb push_back
#define ll long long
#define pii pair<int,int>
#define pcc pair<char,char>
#define F first
#define S second
#define int long long
#define pi 3.141592653589793238462643383279502
#define M  1000000007
#define rep(i,a,n) for(int i=a;i<n;i++)
#define INF 10000000000000000
#define N 305
#define vi vector<int>
#define all(v) v.begin(),v.end()
//#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
int n,m,l;
int a[305][305];
int arr[305][305];
signed main()
{
   ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
   cin>>n>>m>>l;
   rep(i,1,n+1)
   {
       rep(j,1,n+1)
       {
           arr[i][j]=INF;
           if(i == j)a[i][i]=0;
           else
            a[i][j]=INF;
       }
   }
   rep(i,0,m)
   {
       int u,v,w;
       cin>>u>>v>>w;
       a[u][v]=min(a[u][v],w);
       a[v][u]=min(a[v][u],w);
   }
   for(int k=1;k<=n;k++)
   {
       for(int i=1;i<=n;i++)
       {
           for(int j=1;j<=n;j++)
           {
               a[i][j]=min(a[i][j],a[i][k] + a[k][j]);
           }
       }
   }
   for(int i=1;i<=n;i++)
   {
       for(int j=1;j<=n;j++)
       {
           if(a[i][j]<=l)arr[i][j]=1;
       }
   }
   for(int k=1;k<=n;k++)
   {
       for(int i=1;i<=n;i++)
       {
           for(int j=1;j<=n;j++)
           {
               arr[i][j]=min(arr[i][j],arr[i][k] + arr[k][j]);
           }
       }
   }
   int q;
   cin>>q;
   while(q--)
   {
       int s,t;
       cin>>s>>t;
       if(arr[s][t] == INF)
        cout<<-1<<endl;
       else
        cout<<arr[s][t] - 1<<endl;
   }
}


Measured memory_bytes: 2048
n, x = map(int, input().split())
ar = list(map(int, input().split()))
total = 0
for i in range(1, n):
    if ar[i - 1] + ar[i] > x:
        c = ar[i - 1] + ar[i] - x
        if ar[i] >= c:
            ar[i] -= c
        else:
            ar[i] = 0
            ar[i - 1] -= (c - ar[i])
        total += c
print(total)


Measured memory_bytes: 14252
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		Map<Character,Integer> map = new HashMap<>(); 
		for(int i=0;i<n;i++) {
			map.put(sc.next().charAt(0),0);
		}
		Object[] array = map.keySet().toArray();
		if(array.length==4)
		System.out.println("Four");
		else {
			System.out.println("Three");
		}
	}

}


Measured memory_bytes: 21204
import sys
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7

n = I()
k = I()
x = LI()


# xy平面上の（xi, i)にボールが配置されている。つまり各行に対して必ず一つボールがある。
# これを回収する2種類のロボットA,BをN台ずつ用意している。
# Aのi代目を(0, i)に、Bのi代目を(k, i)に設置した。
# Aロボットは、x=0からスタート, Bロボットはx = kからスタートして、各行上のボールを回収して元の位置に戻る。
# 各行のロボットを起動してすべてのボールを回収するとき、ロボットの移動距離の総和の最小値を求めよ
mov = 0

for i in range(n):
    a_m = abs(0 - x[i])
    b_m = abs(k - x[i])
    if a_m < b_m:
        mov += 2 * a_m
    else:
        mov += 2 * b_m

print(mov)


Measured memory_bytes: 62244
#include <iostream>
#include <string>
#include <map>
#include <math.h>
#include <complex>

using namespace std;

int main(){

    int a[10];

    for(int i=0;i<6;i++){
        cin>>a[i];
    }

    int min1 = a[0];
    int answer = 0;
    int count=0;

    for(int i=0;i<4;i++){
        if(a[i]<min1) min1 = a[i];
    }
    
    for(int i=0;i<4;i++){
        if(a[i]!=min1){
        answer += a[i];
        count++;
        }
    }

    if(count!=3){
        for(int i=0;i<3-count;i++) answer += min1;
    }

    if(a[4]>a[5]) answer += a[4];
    else answer += a[5];

    cout<<answer<<endl;

    return 0;


}


Measured memory_bytes: 3112
while(1)
h,w=gets.chomp.split(" ").map(&:to_i)
if(w==0&&h==0)
 break
end
j=0
while(j<h)
 i=0
 while(i<w)
  if(i*j*(w-i-1)*(h-j-1)==0)
   print"#"
  else
   print"."
  end
  i=i+1
 end
 print"\n"
 j=j+1
end
 print"\n"
end



Measured memory_bytes: 6848
def main():
    N,K = map(int, input().split())
    p = [int(i) for i in input().split()]

    tmp_max = sum(p[:K])
    tmp = sum(p[:K])
    for i in range(N-K):
        tmp += p[K+i]
        tmp -= p[i]

        if tmp > tmp_max:
            tmp_max = tmp

    ans = (tmp_max + K) / 2
    print(ans)


if __name__ == "__main__":
    main()


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

int main()
{
	int a,b;
	cin >> a >> b;
	int temp = b, temp2 = 1;
	while(temp > 0)
	{
		temp /= 10;
		temp2 *= 10;
	}
	temp = a * temp2 + b;
	for (int i = 0; i <= 1005; ++i)
	{
		if (i*i == temp)
		{
			cout << "Yes" << endl;
			return 0;
		}
	}
	cout << "No" << endl;
	return 0;
}

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

#ifdef LOCAL
#include "/home/shahraaz/bin/debug.h"
#else
#define db(...)
#endif

using ll = long long;
#define f first
#define s second
#define pb push_back
#define all(v) v.begin(), v.end()

const int NAX = 2e5 + 5, MOD = 1000000007;

class Solution
{
private:
public:
    Solution() {}
    ~Solution() {}
    void solveCase()
    {
        int n, k;
        cin >> n >> k;
        vector<int> p(n);
        for (auto &x : p)
        {
            cin >> x;
        }
        sort(all(p));
        cout << accumulate(p.begin(), p.begin() + k, 0LL) << '\n';
    }
};

int32_t main()
{
#ifndef LOCAL
    ios_base::sync_with_stdio(0);
    cin.tie(0);
#endif
    int t = 1;
    // cin >> t;
    Solution mySolver;
    for (int i = 1; i <= t; ++i)
    {
        mySolver.solveCase();
#ifdef LOCAL
        cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n";
        TimeStart = chrono::steady_clock::now();
#endif
    }
    return 0;
}


Measured memory_bytes: 3620
#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iomanip>
#include <iterator>
#include <algorithm>
#include <functional>
#include <typeinfo>
#include <utility>
#include <tuple>

using namespace std;

#define repr(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rep(i, n) repr(i, 0, n)
#define reprrev(i, a, b) for (int i = (int)(b) - 1; i >= (int)(a); i--)
#define reprev(i, n) reprrev(i, 0, n)

#define PI M_PI
#define INF 1000000000;
#define MOD 1000000007;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<bool> vb;
typedef vector<string> vs;
typedef vector<vector<int>> vvi;
typedef vector<vector<ll>> vvll;
typedef vector<vector<bool>> vvb;
typedef vector<vector<string>> vvs;

constexpr int dir[4][2] = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

ll Pow(ll a, ll b, ll mod) {
	ll x = 1;
	while (b > 0) {
		if (b & 1) x = x * a;
		a = a * a;
		b = b >> 1;
	}
	return x;
}


/*<ここから>***********************************************************/

int N;
int a[100000] = { 0 };

int main()
{
	cin >> N;
	rep(i, N) {
		int n;
		cin >> n;
		a[n]++;
	}

	int res = 0;
	rep(i, 100000) {
		int c = 0;

		if (i > 0) c += a[i - 1];
		c += a[i];
		if (i < 99999) c += a[i + 1];

		if (res < c) res = c;
	}

	cout << res << endl;

	return 0;
}


Measured memory_bytes: 764
N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = input()
flag = [0]*N
ans = 0
for i in range(N):
    if i-K>=0 and T[i-K] == T[i] and flag[i-K]:
        continue
    if T[i] == 'r':
        ans+=P
    elif T[i] == 's':
        ans+=R
    else:
        ans+=S
    flag[i] = True
print(ans)

Measured memory_bytes: 43748