akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
typedef long long ll; 
const ll mod = 1e9+7;
#define fo(i, n) for (int i = 0; i < n; i++)
#define sc(n) scanf("%d", &n) 
using namespace std;

int n, m;

void solve() {
    sc(n); sc(m);
    int sum = 0;
    int a;
    fo(i, m) {
        sc(a);
        sum += a;
    }
    n -= sum;
    if (n >= 0) printf("%d", n);
    else printf("%d", -1);
}

int main() {
    int t = 1;
    //scanf("%d", &t);
    while (t--) {
        solve();
    }
    return 0;
}

Measured memory_bytes: 3260
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
	double a,b,h,m;
	cin>>a>>b>>h>>m;
	double angle=abs(h*30-m*6+0.5*m);	
	cout<<fixed<<setprecision(20)<<sqrt(a*a+b*b-2*a*b*cos(angle*3.1415926536/180));
}

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

int main(){
    int N;
    cin >> N;
    vector<int> A(N);
    rep(i,N){
        cin >> A.at(i);
    }
    sort(A.begin(),A.end());
    cout << abs(A.at(0)-A.at(N-1));
}

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

typedef long long ll;

int main(){
  ll x, y, a, b, c;
  cin >> x >> y >> a >> b >> c;
  vector<ll> p(a); rep(i, a) cin >> p[i];
  vector<ll> q(b); rep(i, b) cin >> q[i];
  vector<ll> r(c); rep(i, c) cin >> r[i];
  sort(p.begin(), p.end());
  sort(q.begin(), q.end());
  rep(i, x) r.push_back(p[a-i-1]);
  rep(i, y) r.push_back(q[b-i-1]);
  sort(r.begin(), r.end());
  
  ll ans = 0;
  ll size = r.size();
  rep(i, x+y) ans += r[size-i-1];
  cout << ans << endl;
  
  return 0;
}

Measured memory_bytes: 5488
/*|In The Name Of Allah|*/

#include <bits/stdc++.h>

using namespace std;

const int N = 1e2+5;

const int mod = 1e9+7;

int n;
int cnt[N];

vector < int > primeFactors(long long num){
    vector < int > prm;
    while (num % 2 == 0){
        prm.push_back(2);
        num = num/2;
    }
    for (long long i = 3; i*i <= num; i = i + 2){
        while (num % i == 0){
            prm.push_back(i);
            num = num/i;
        }
    }
    if (num > 2)
        prm.push_back(num);
    return prm;
}

int go(int idx , int mul , int tk){
    if(mul > 75)
        return 0;
    if(idx > 100)
        return mul == 75;
    int ways = go(idx + 1 , mul * max(tk+1 , 1) , 0);
    if(tk + 1 <= cnt[idx])
        ways += go(idx , mul , tk + 1);
    return ways;
}

int main(){
    scanf("%d" , &n);
    for(int i = 1; i <= n; i++){
        vector < int > ret = primeFactors(i);
        for(auto v : ret){
            cnt[v]++;
        }
    }
    printf("%d\n" , go(1 , 1 , 0));
}

Measured memory_bytes: 256
#include<iostream>
using namespace std;
int main(){
    int suma=0,sumb=0;
    int a[4],b[4];
    int mina=2999,minb=2999;
    for(int i=0;i<4;i++){
        cin>>a[i];
        if(mina>a[i]) mina=a[i];
        suma=suma+a[i];
    }
    for(int k=0;k<2;k++){
        cin>>b[k];
        if(minb>b[k]) minb=b[k];
        sumb=sumb+b[k];
    }
    cout<<suma+sumb-mina-minb<<endl;
    return 0;
}

Measured memory_bytes: 3116
import java.util.*;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;

import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
 
public class Main{
    static long mod=1000000007;
//    static int dx[]={-1,0,1,0};
//    static int dy[]={0,-1,0,1};

    public  static void main(String[] args)   throws Exception, IOException{        
        Reader sc = new Reader(System.in);
        PrintWriter out=new PrintWriter(System.out);

        int n = sc.nextInt();
        int a[]=sc.nextIntArray(n);
        int f=0,m=1<<28;
        long ans=0;
        for (int i = 0; i < n; i++) {
			if(a[i]==0) {f+=1000000;}
			f+=a[i]<0?1:0;
			ans+=abs(a[i]);
			m=min(abs(a[i]),m);
		}
        if(f<100005 && f%2==1) {
        	ans-=m*2;
        }

        out.println(ans);
        out.flush();
    }

    static boolean validpos(int x,int y,int r, int c){
        return x<r && 0<=x && y<c && 0<=y;
    }

    static void db(Object... os){
        System.err.println(Arrays.deepToString(os));
    }  
}

//class P {
//    int id, d;
//    P(int  id, int d) {
//        this.id=id;
//        this.d=d;
//    }
//}

//class P implements Comparable<P>{
//    int id,T;
//    P(int id, int T) {
//        this.id=id;
//        this.T=T;
//    }
//    public int compareTo(P p){
//        return id-p.id; //des
//    }
//}

class Reader
{ 
    private BufferedReader x;
    private StringTokenizer st;
    
    public Reader(InputStream in)
    {
        x = new BufferedReader(new InputStreamReader(in));
        st = null;
    }
    public String nextString() throws IOException
    {
        while( st==null || !st.hasMoreTokens() )
            st = new StringTokenizer(x.readLine());
        return st.nextToken();
    }
    public int nextInt() throws IOException
    {
        return Integer.parseInt(nextString());
    }
    public int[] nextIntArray(int size) throws IOException{
    	int r[] = new int[size];
    	for (int i = 0; i < size; i++) {
			r[i] = this.nextInt(); 
		}
    	return r;
    }
    public long[] nextLongArray(int size) throws IOException{
    	long r[] = new long[size];
    	for (int i = 0; i < size; i++) {
			r[i] = this.nextLong(); 
		}
    	return r;
    }
    public long nextLong() throws IOException
    {
        return Long.parseLong(nextString());
    }
    public double nextDouble() throws IOException
    {
        return Double.parseDouble(nextString());
    }
}


Measured memory_bytes: 42056
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Math;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            D();
        }

        static void D()
        {
            var Q = ReadInt();
            var lrList = new List<List<int>>();
            var max = 0;

            for (int i = 0; i < Q; i++)
            {
                var lr = ReadSplitInt();
                max = Max(max, lr[0]);
                max = Max(max, lr[1]);
                lrList.Add(lr);
            }

            var a = new int[max+1];
            for (int i = 1; i <= max; i++)
            {
                if (IsPrime(i) && IsPrime((i + 1) / 2))
                    a[i] = 1;
            }

            var s = new int[a.Length + 1];
            for (int i = 1; i < a.Length; i++)
                s[i + 1] = s[i] + a[i];

            foreach (var lr in lrList)
            {
                var left = lr[0];
                var right = lr[1];
                Println(s[right + 1] - s[left]);
            }
        }

        static IEnumerable<int> Range(int start, int stop)
        {
            if (start < 0 || stop < 0 || start > stop || (start <= 0 && stop <= 0))
                return new List<int>();

            return Enumerable.Range(start, stop - start);
        }

        static bool IsDigit(string str)
        {
            var i = 0;
            return int.TryParse(str, out i);
        }

        static int DigitsSum(long num)
        {
            return num.ToString().Select(x => x.ToString()).Sum(int.Parse);
        }

        static int[] ToIntArray(string str)
        {
            return str.Select(x => x.ToString()).Select(int.Parse).ToArray();
        }

        static int Gcd(int a, int b) => b == 0 ? a : Gcd(b, a % b);

        static bool IsPrime(int x)
        {
            if (x <= 1 || (x != 2 && x % 2 == 0)) return false;
            if (x == 2) return true;

            for (int i = 3; i < x; i += 2)
                if (x % i == 0) return false;

            return true;
        }

        static string Read() => Console.ReadLine();
        static int ReadInt() => int.Parse(Read());
        static long ReadLong() => long.Parse(Read());

        static List<string> ReadSplit() => Read().Split().ToList();
        static List<int> ReadSplitInt() => Read().Split().Select(int.Parse).ToList();
        static List<long> ReadSplitLong() => Read().Split().Select(long.Parse).ToList();

        static void Print(object value) => Console.Write(value.ToString());
        static void Println(object value) => Console.WriteLine(value.ToString());

        static string Join<T>(IEnumerable<T> list) => string.Join("", list);
    }

    public static class MyExtensions
    {
        public static string Slice(this string str, int start = 0, int stop = 0)
        {
            if (start > str.Length || stop > str.Length || start < 0 || stop < 0)
                return "";

            if (stop == 0) stop = str.Length;
            return str.Substring(start, stop - start);
        }
    }
}



Measured memory_bytes: 31148
#include <bits/stdc++.h>
using namespace std;
//Author: Ezio Sam
/* Shorthands */
#define ll long long
#define pb push_back
#define em emplace_back
#define mp make_pair
#define sp " "
#define cs "Case "
#define fi first
#define sn second

/* STL */
#define mem(a,n) memset(a, n, sizeof(a));
#define all(x) x.begin(),x.end()
#define alr(x) x.rbegin(),x.rend()
#define sz(x)  (int)x.size()
#define mx(v)  *max_element(v.begin(),v.end())
#define mxi(v) distance(v.begin(),max_element(v.begin(),v.end()))
#define mxa(a) *max_element(a, a.size())
#define r(a)   reverse(a.begin(),a.end())
/* loops */
#define fr(i,n)   for(__typeof(n) i=0;i<(n);i++)
#define fn(i,n)   for(__typeof(n) i=1;i<=(n);i++)
/*Special*/
#define Ezio ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define db(something)  cerr<<#something<<" - "<<something<<"\n";

int main()
{

   Ezio
   ll t,m,n,x,a,b,c;
   string s;

   cin>>a>>b>>c>>n;

   while(a>=b and n>0){
    n--;
    b*=2;
   }
   if(a>=b){
    cout<<"No"<<endl;
    return 0;
   }
   while(b>=c and n>0){
    n--;
    c*=2;
   }

   cout<<(b>=c?"No":"Yes")<<endl;

   return 0;
}


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

typedef long long ll;
typedef pair<int,int> p_int;
typedef pair<ll,ll> p_ll;
typedef tuple<ll,ll,ll> t3_ll;
int dx[] = {-1,0,1,0},dy[] = {0,1,0,-1};
int prime[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};
const ll inf = 1000000007;

int main() {
	int n;
	cin >> n;
	int h[n];
	int dp[n];
	for (int i = 0;i < n;i++) {
		cin >> h[i];
		dp[i] = inf;
	}
	dp[0] = 0;
	for (int i = 0;i < n;i++) {
		if (i+1 < n) {dp[i+1]=min(dp[i+1],dp[i]+abs(h[i+1]-h[i]));}
		if (i+2 < n) {dp[i+2]=min(dp[i+2],dp[i]+abs(h[i+2]-h[i]));}
	}
	cout << dp[n-1] << endl;
}

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

int main() {
	int n, d;
	cin >> n >> d;
	int x[n][d];
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < d; j++) {
			cin >> x[i][j];
		}
	}

	int count = 0;
	for (int i = 0; i < n - 1; i++) {
		for (int j = i + 1; j < n; j++) {
			int l = 0;
			for (int k = 0; k < d; k++) {
				l += (x[i][k] - x[j][k]) * (x[i][k] - x[j][k]);
			}
			for (int k = 1; k * k <= l; k++) {
				if (k * k == l) {
					count++;
				}
			}
		}
	}

	cout << count << endl;
}


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

int main(){
    bool ans = 1;
    int n;
    cin >> n;
    vector<long long> h(n);

    cin >> h.at(0);

    for(int i = 1;i < n;i++){
        cin >> h.at(i);
    }


    for(int i = n - 1;i >= 1;i--){
        
        if(h.at(i) < h.at(i - 1)){
            h[i - 1] -= 1;
        }
        
    }
    

    for(int i = 1;i < n;i++){
        if(h.at(i - 1) > h.at(i)){
            ans = 0;
            break;
        }
    }
    


    int count = 0;

    if(count == n){
        ans = 1;
    }

    if(ans){
        cout << "Yes" << endl;
    }
    else{
        cout << "No" << endl;
    }

    return 0;
}

Measured memory_bytes: 1152
#include<bits/stdc++.h>
using namespace std;
long long a,b,cnt=1;
int main()
{
	scanf("%lld%lld",&a,&b);
	while(1)
	{
		a*=2;
		if(a>b)
		{
			break;
		}
		++cnt;
	}	
	printf("%lld\n",cnt);
}

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

using namespace std;

typedef pair<int,int>   II;
typedef vector< II >      VII;
typedef vector<int>     VI;
typedef vector< VI > 	VVI;
typedef long long int 	LL;

#define PB push_back
#define MP make_pair
#define F first
#define S second
#define SZ(a) (int)(a.size())
#define ALL(a) a.begin(),a.end()
#define SET(a,b) memset(a,b,sizeof(a))
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) FOR(i, 0, n)

#define si(n) scanf("%d",&n)
#define dout(n) printf("%d\n",n)
#define sll(n) scanf("%lld",&n)
#define lldout(n) printf("%lld\n",n)
#define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL)

#define TRACE

#ifdef TRACE
#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
	cerr << name << " : " << arg1 << std::endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
	const char* comma = strchr(names + 1, ',');cerr.write(names, comma - names) << " : " << arg1<<" | ";__f(comma+1, args...);
}
#else
#define trace(...)
#endif

//FILE *fin = freopen("in","r",stdin);
//FILE *fout = freopen("out","w",stdout);

const int N = 1e4 + 10;
int A[N], B[N];
int main()
{
  int n;si(n);
  LL sa = 0, sb = 0;
  REP(i, n){
    si(A[i]);
    sa += A[i];
  }
  REP(i, n){
    si(B[i]);
    sb += B[i];
  }
  LL nop = sb - sa;
  if(nop < 0){
    puts("No");
    return 0;
  }
  LL opa = 0, opb = 0;
  REP(i, n){
    if(A[i] < B[i]){
      opa += (B[i] - A[i] + 1) / 2;
      A[i] += ((B[i] - A[i] + 1) / 2) * 2;
    }
    if(B[i] < A[i]){
      opb += A[i] - B[i];
      B[i] = A[i];
    }
  }
  opa = nop - opa;
  opb = nop - opb;
  if(opa < 0 || opb < 0 || (2 * opa != opb)){
    puts("No");
  }
  else {
    puts("Yes");
  }

	return 0;
}

Measured memory_bytes: 384
N = int(input())
A = input().split()
B = input().split()
A = [int(a) for a in A]
B = [int(b) for b in B]

sum_ = 0

for i in range(N):
    if(A[i]>B[i]):
        sum_ += B[i]
    else:
        sum_ += A[i]
        next_attack = min([B[i]-A[i],A[i+1]])
        A[i+1] -= next_attack
        sum_ += next_attack
print(sum_)

Measured memory_bytes: 21824
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i,n) for(long long i=0; i<(int)n; i++)
#define rep2(i,a,n) for(long long i=(a); i<(int)(n); i++)
#define all(vec) vec.begin(),vec.end()
using vi = vector<int>;
using vs = vector<string>;
using vvi = vector<vi>;
using pii = pair<int, int>;
using psi = pair<string, int>;
const int dx[4] = {1, 0,-1, 0};
const int dy[4] = {0, 1, 0,-1};
const int mod = 1e9+7;
int gcd(int a, int b){if(a%b == 0){return(b);}else{return(gcd(b, a%b));}}
int lcm(int a, int b){return a * b / gcd(a, b);}

int N, M, K, H, W, L, R, X;
string S, T;

signed main(){
  int A, B; cin >> A >> B >> S;
  N = S.size();
  rep(i,N){
    if(i<A && S[i] != '-') continue;
    if(i==A && S[i] == '-') continue;
    if(i>A && S[i] != '-') continue;
    cout << "No" << endl;
    return 0;
  }
  cout << "Yes" << endl;
  return 0;
}


Measured memory_bytes: 3604
n,a,b = map(int,input().split())
s = input()
x = a + b
y = 1
z = 1
for i in range(n):
    if s[i] == 'a':
        if y <= x:
            print('Yes')
            y += 1
        else:
            print('No')
    elif s[i] == 'b':
        if y <= x and z <= b:
            print('Yes')
            y += 1
            z += 1
        else:
            print('No')
    else:
        print('No')

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

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

	int N, K; cin >> N >> K;
	int a[210000];
	for (int i = 0; i < N; i++) {
		cin >> a[i];
	}
	sort(a, a + N);
	int cnt = 1;
	int z = 1;
	vector<int> b;
	for (int i = 1; i < N; i++) {
		if (a[i - 1] != a[i]) {
			cnt++;
			b.push_back(z);
			z = 1;
		}
		else z++;
	}
	b.push_back(z);
	if (cnt <= K) {
		cout << 0;
		return 0;
	}
	K = cnt - K;
	int sum = 0;
	sort(b.begin(), b.end());
	while (K>0) {
		sum += b[K - 1];
		K--;
	}
	cout << sum;
}

Measured memory_bytes: 2168
#include <stdio.h>
#include <cstdio>
#include <queue>
#include <set>
using namespace std;

int main(){
  
  /* read input */
  int N;
  int total = 0;
  int max = 0;
  int tmp;
  
  scanf("%d", &N);
  
  for(int i = 0; i < N; i++){
    scanf("%d", &tmp);
    total += tmp;
    if(tmp > max) max = tmp;
  }
  total -= max/2;
  
  printf("%d", total);
  
  return 0;
}


Measured memory_bytes: 128
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
using pi = pair<int, int>;

    const int M=1e9+7;

    long long mod(long long x)
    {
        return ((x%M + M)%M);
    }

    long long add(long long a, long long b){
        return mod(mod(a)+mod(b));
    }

    long long mul(long long a, long long b){
        return mod(mod(a)*mod(b));
    }

    long long minu(long long a, long long b){
        return mod(mod(a)-mod(b));
    }

    ll modPow(ll a, ll b){
        if(b==0)
            return 1LL;
        if(b==1)
            return a%M;
        ll res=1;
        while(b){
            if(b%2==1)
                res=mul(res,a);
            a=mul(a,a);
            b=b/2;
        }
        return res;
    }
int main()
{
    int t = 1;
    //cin >> t;
    while(t--)
    {
       ll n;
       cin >> n;
       if(n == 1)cout << 0 << endl;
       else if(n == 2)cout << 2 << endl;
       else
       {
           ll ans = minu(add(modPow(10LL, n), modPow(8LL, n)), mul(2LL, modPow(9LL, n)));
           cout << ans << endl;
       }
    }
}


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

using namespace std;
int main(){
 int n;
  cin >> n;
  
  vector<long> c(n),s(n),f(n);
  
  for(int i=0;i<n-1;i++) cin >> c[i] >> s[i] >> f[i];
   
  for(int i=0;i<n;i++){
    long t=0;
    for(int j=i;j<n-1;j++){
     if(t<s[j]) t=s[j];
     else if(t%f[j]==0) ;
     else t=t+f[j]-(t%f[j]); 
     t+=c[j];
    }
    cout << t << endl;
  }          
  
}

Measured memory_bytes: 256
#include<stdio.h>

const int INF = 1000000000;

struct Edge{
  int a;
  int b;
  int c;
};

int min(int a, int b){
  return a < b ? a : b;
}

int main(){
  int N, M;
  scanf("%d%d", &N, &M);
  
  int dist[N][N];
  for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
      if(i == j) dist[i][j] = 0;
      else dist[i][j] = INF;
    }
  }
  
  struct Edge edge[M];
  for(int e = 0; e < M; e++){
    scanf("%d%d%d", &edge[e].a, &edge[e].b, &edge[e].c);
    edge[e].a--;
    edge[e].b--;
    dist[edge[e].a][edge[e].b] = edge[e].c;
    dist[edge[e].b][edge[e].a] = edge[e].c;
  }
  
  for(int k = 0; k < N; k++){
    for(int i = 0; i < N; i++){
      for(int j = 0; j < N; j++){
        dist[i][j] = min(dist[i][k] + dist[k][j], dist[i][j]);
      }
    }
  }
  
  int candidates = 0;
  
  for(int e = 0; e < M; e++){
    int s = 0;
    for(int i = 0; i < N; i++){
      for(int j = 0; j < N; j++){
        if(dist[i][edge[e].a] + edge[e].c + dist[edge[e].b][j] == dist[i][j]){
          s = 1;
        }
      }
    }
    
    if(!s) candidates++;
  }
  
  printf("%d\n", candidates);
  
  return 0;
}

Measured memory_bytes: 256
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

#[allow(dead_code)]
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

fn main() {
    let v = read_vec::<i32>();
    let n = v[0];
    let l = v[1];

    let mut tastes = Vec::new();
    for i in 1..n+1 {
        tastes.push(l + i - 1);
    }

    let mut minabs = 10000000;
    let mut minj = 0;
    for j in tastes {
        if j.abs() < minabs {
            minabs = j.abs();
            minj = j;
        }
    }

    let sum_n = (l - 1) * n + (n * (n + 1) / 2);
    let sum_n_ = sum_n - minj;

    println!("{}", sum_n_);
}


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

using namespace std;

const int N = 100 * 1000 + 17;
const int MOD = 1000 * 1000 * 1000 + 7;
const int MAGIC = 512;

struct edge {
    int u, v, col, len;
    edge() = default;
    edge(int u, int v, int c, int l) : u(u), v(v), col(c), len(l) { }
};

int n, q, t = 0;
int L[N], R[N];
int up[N][20];
vector< pair<long long, int> > sum[N];
vector<edge> g[N];
vector<edge> E[N];

bool read() {
    if (!(cin >> n >> q))
        return false;

    sum[n].resize(n);

    for (int i = 0; i < n - 1; ++i) {
        int u, v, col, len;
        cin >> u >> v >> col >> len;
        g[u - 1].emplace_back(u - 1, v - 1, col, len);
        g[v - 1].emplace_back(v - 1, u - 1, col, len);
        E[col - 1].emplace_back(u - 1, v - 1, col, len);
    }

    return true;
}

pair<long long, int> operator+(const pair<long long, int>& a, const pair<long long, int>& b) {
    return { a.first + b.first, a.second + b.second };
}

void predfs(int v, int pr) {
    up[v][0] = pr;
    L[v] = t++;

    for (const auto& e : g[v])
        if (e.v != pr)
            predfs(e.v, v);

    R[v] = t - 1;
}

void dfs(int v, int pr, int id) {
    for (const auto& e : g[v])
        if (e.v != pr) {
            if (id != n)
                sum[id][e.v] = sum[id][e.v] + sum[id][v];
            else
                sum[id][e.v] = sum[id][v] + make_pair(e.len, 1);

            dfs(e.v, v, id);
        }
}

bool isanc(int u, int v) { return L[u] <= L[v] && R[v] <= R[u]; }

bool btwn(int u, int v, int U, int V) {
    if (!isanc(u, U) || !isanc(V, u))
        return false;

    if (!isanc(v, U) || !isanc(V, v))
        return false;

    return true;
}

int lca(int u, int v) {
    if (isanc(u, v))
        return u;

    if (isanc(v, u))
        return v;

    for (int i = 19; i >= 0; --i)
        if (!isanc(up[u][i], v))
            u = up[u][i];

    return up[u][0];
}

void solve() {
    predfs(0, 0);

    for (int i = 0; i < n; ++i)
        if (E[i].size() >= MAGIC) {
            sum[i].resize(n);

            for (const auto& e : E[i])
                sum[i][isanc(e.u, e.v) ? e.v : e.u] = { e.len, 1 };

            dfs(0, 0, i);
        }

    sum[n].resize(n);
    dfs(0, 0, n);

    for (int k = 1; k < 20; ++k)
        for (int i = 0; i < n; ++i)
            up[i][k] = up[up[i][k - 1]][k - 1];

    while (q --> 0) {
        int col, w, u, v;
        cin >> col >> w >> u >> v;
        --col, --u, --v;
        auto anc = lca(u, v);
        auto res = sum[n][u].first + sum[n][v].first - 2 * sum[n][anc].first;

        if (E[col].size() >= MAGIC) {
            res -= sum[col][u].first + sum[col][v].first - 2 * sum[col][anc].first;
            res += w * (sum[col][u].second + sum[col][v].second - 2 * sum[col][anc].second);
        } else {
            for (const auto& e : E[col])
                if (btwn(e.u, e.v, u, anc) || btwn(e.u, e.v, v, anc))
                    res += w - e.len;
        }

        cout << res << endl;
    }
}

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    while (read())
        solve();

    return 0;
}



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

using namespace std;

int main() {
    int N, Q, l[100000], r[100000];
    string S;
    cin >> N >> Q >> S;
    int r_sum[100000] = {0};
    for(int i = 1; i <= N; ++i){
        r_sum[i] = r_sum[i-1]+(S[i-1]=='A'&&S[i]=='C');
    }
    for(int i = 0; i < Q; ++i) {
        cin >> l[i] >> r[i];
        cout << r_sum[r[i]-1] - r_sum[l[i]-1] << endl;
    }
    return 0;
}

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

#define SZ(x) ((int)(x).size())
#define ALL(x) (x).begin(),(x).end()

#define FOR(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define REP(i,x) for(int i=0;i<(int)(x);i++)
#define REPS(i,x) for(int i=1;i<=(int)(x);i++)
#define RREP(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define RREPS(i,x) for(int i=((int)(x));i>0;i--)

typedef pair<int, int> pint;

#define mp make_pair
#define mt make_tuple
#define pb push_back
#define pf push_front

#define MOD (1000 * 1000 * 1000 + 7)

signed main() {
    int N, M;
    cin >> N >> M;

    vector<pair<int, int>> ba;
    REP(i, M) {
        int a, b;
        cin >> a >> b;
        ba.pb(make_pair(b, a));
    }

    sort(ALL(ba));

    int ans = 0;
    int prev = -1;
    for (pair<int, int> e: ba) {
        if (e.second > prev) {
            prev = e.first - 1;
            ans++;
        }
    }

    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 1400
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in);) {
            int x = scanner.nextInt();
            int ans = 0;
            if (x == 0) {
                ans = 1;
            }
            System.out.println(ans);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Measured memory_bytes: 35668
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
inline int read(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-')f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=(x<<3)+(x<<1)+c-'0';
        c=getchar();
    }
    return x*f;
}
int n,a,b;
ll qpow(ll a,ll b){
	ll ans=1;
	while(b){
		if(b&1)ans=ans*a%mod;
		a=a*a%mod;
		b>>=1;
	}
	return ans;
}
ll C(ll n,ll m){
	ll ans=1;
	for(int i=n;i>=n-m+1;i--){
		ans=ans*i%mod;
	}
	for(int i=1;i<=m;i++){
		ans=ans*qpow(i,mod-2)%mod;
	}
	return ans;
}
int main(){
	n=read(),a=read(),b=read();
	printf("%lld\n",(qpow(2LL,n)-C(n,a)-C(n,b)-1+mod+mod)%mod);
	return 0;
}


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

using namespace std;

#define ll long long
#define mod 1000000007

void solve(){

    int n; cin >> n;
    int arr[n];
    for(int i = 0; i < n; ++i) cin >> arr[i];
    int dp[n];
    dp[0] = 0, dp[1] = abs(arr[1] - arr[0]);
    for(int i = 2; i < n; ++i){
        dp[i] = min(dp[i-2] + abs(arr[i-2]-arr[i]), dp[i-1] + abs(arr[i-1]-arr[i]));
    }
    cout << dp[n-1] << endl;
    return;
}

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

Measured memory_bytes: 4396
#define D(x) cout << #x " = " << x << endl
#define DD(x, y) cout << "(" #x ", " #y ") = (" << x << ", " << y << ")" << endl
#define DDD(x, y, z) cout << "(" #x ", " #y ", " #z ") = (" << x << ", " << y << ", " << z << ")" << endl
#define DV(v) for (auto __macro_vi : v){ cout << __macro_vi << " ";} cout << endl;
#define DA(a, n) for (int __macro_i = 0; __macro_i < n; ++__macro_i) { cout << a[__macro_i] << " "; } cout << endl;
#define REP(i, n) for (int i = 0; i < n; ++i)
#define ALL(v) (v).begin(), (v).end()
#include<iostream>
#include<vector>
#include<cassert>
#include<cmath>
template<class T, class U> std::ostream& operator<<(std::ostream& os, const std::pair<T, U>& p){ os << "(" << p.first << ", " <<  p.second << ")"; return os; }

using namespace std;

int n;
vector<int> color;
vector<vector<int>> ans;
int anscnt = 0;
int get_ans(int i, int j) {
    return ans[i][j];
}
void set_ans(int i, int j, int level) {
    // DD(i, j);
    ans[i][j] = level;
    ans[j][i] = level;
    ++anscnt;
}

void dfs(int node, int level, int c = 1) {
    color[node] = c;
    REP(i, n) {
        if (i == node || get_ans(i, node) != -1) continue;
        if (color[i] != -1 && color[i] != color[node]) set_ans(node, i, level);
        if (color[i] == -1) dfs(i, level, c == 1 ? 2 : 1);
    }
}
int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);
    cin >> n;
    // D(n);
    color = vector<int>(n);
    ans = vector<vector<int>>(n, vector<int>(n, -1));
    int level = 1;
    while(anscnt != n * (n - 1) / 2) {
        color.assign(n, -1);
        REP(i, n) {
            if (color[i] == -1) dfs(i, level);
        }
        // D(anscnt);
        // D(level);
        level++;
    }

    REP(i, n - 1) {
        for (int j = i + 1; j < n - 1; ++j) {
            cout << ans[i][j] << " ";
        }
        cout << ans[i][n - 1] << endl;
    }
}


Measured memory_bytes: 1536
// Created by sz
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 5;
int n, d[N];
typedef pair<int, int> pii;
vector<pii> g[N];

void dfs(int u, int dis, int p){
    d[u] = dis;
    for(auto i: g[u]){
        if(i.first == p)continue;
        dfs(i.first, d[u] + i.second, u);
    }
}

int main(){
#ifdef LOCAL
    freopen("./input.txt", "r", stdin);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    cin>>n;
    int u,v,w;
    for (int i = 0; i < n-1; i++){
        cin>>u>>v>>w;
        g[u].push_back({v,w});
        g[v].push_back({u, w});
    }
    

    dfs(1, 0 , -1);
    
    for (int i = 1; i <= n; i++){
        if(d[i]%2==0)cout<<0<<endl;
        else cout<<1<<endl;
    }
    
    
    return 0;
}



Measured memory_bytes: 8448
#include <stdio.h>
#define N 100000
 
int BinarySearch(int, int *, int);
 
int main()
{
  int i, j;
  int n, q;
  int nl[N], s;
  int count = 0;
 
  scanf("%d", &n);
  for(i = 0; i < n; i++)
    {
      scanf("%d", &nl[i]);
    }
 
  scanf("%d", &q);
  for(i = 0; i < q; i++)
    {
      scanf("%d", &s);
      if(BinarySearch(n, nl, s) == 1) 
    {
      count++;
    }
    }
  printf("%d\n", count);
 
  return 0;
}
 
int BinarySearch(int n, int *nl, int s)
{
  int left, mid, right;
 
  left = 0;
  right = n;
  mid = (left + right) / 2;
 
  while(nl[mid] != s)
    {
      if(left + 1 == right) return 0;
      if(nl[mid] < s) left = mid;
      else right = mid;
 
      mid = (left + right) / 2;
    }
 
  return 1;
}

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

typedef long long int  ll;
#define int ll


/* Driver program to test above functions */
int32_t main()
{

    int n;
    cin>>n;
    int count = 0;
    int temp = n;
    int level = 1;
    int attack = 0;
    while(temp){
        temp = temp/2;
        attack += level;
        level *= 2;
    }
    cout<<attack<<endl;
}




Measured memory_bytes: 256
import sys
input = sys.stdin.readline

N, K = map(int, input().split())
R, S, P = map(int, input().split())
T = list(input().rstrip())
# if (i)th == (i-K)th: point=0
for i in range(K,N):
  if T[i] == T[i-K]:
    T[i] = 'o'
    
point = 0
for t in T:
  if t == 'r':
    point += P
  elif t == 's':
  	point += R
  elif t == 'p':
    point += S

print(point)


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

using namespace std;

#define precision(n)   cout << setprecision(n) << fixed
#define sf(a)          scanf("%d",&a)
#define sf2(a,b)       scanf("%d %d",&a,&b)
#define pi             3.1415926535
#define eps            0.0000000001
#define gl(a)          scanf("%llu",&a)
#define mod            1000000007
#define pf             printf
#define loop(ds,itr)   for ( auto itr = ds.begin(); itr != ds.end(); itr++ )
#define fr(i,n)        for ( int i = 0; i < n; i++ )
#define bug            cout << 'x' << endl;
#define check(x)       cout << x << endl;
#define f              first
#define s              second
#define e              2.71828182845
#define mp             make_pair
#define min4(a,b,c,d)  min(a,min(b,min(c,d)));
#define inf            0x3f3f3f3f
///#define MAX            100005
#define srt(n)         (int)(sqrt(double(n))+eps)
#define power(n,i)     (long long)ceil(pow(n,i))



#ifdef FACT
     #include <ctime>
     clock_t tStart = clock();
     #define debug(args...) {dbg,args; cerr<<endl;}
     #define timeStamp debug ("Execution Time: ", (double)(clock() - tStart)/CLOCKS_PER_SEC)
     #define bug printf("%d\n",__LINE__);

#else
    #define debug(args...)
    #define timeStamp

#endif

struct debugger{
    template<typename T> debugger & operator , (const T& v){
        cerr<<v<<" ";
        return *this;
    }
}dbg;


typedef long long ll;
typedef unsigned long long ull;
typedef pair < ll,int > ii;
typedef priority_queue< int,vector<int>, greater<int> > pq_increasing;

const int MAX = int(int(1e7) >> 6);
int marked[MAX+5];
vector <int> primes;
vector <ii> factors;

#define on(n)      ( marked[int(n>>6)] & ( 1 << (int(n>>1) & 31) ) )
#define mark(n)    marked[int(n>>6)] |= ( 1 << (int(n>>1) & 31) )

void sieve ( int n ) {
    int sqrtN = sqrt(n)+1;
    for ( int i = 3; i <= sqrtN; i += 2 ) {
        if ( !on(i) ) {
            for ( int j = i*i; j <= n; j += 2*i ) mark(j);
        }
    }
    primes.push_back(2);
    for ( int i = 3; i <= n; i += 2 ) if ( !on(i) ) primes.push_back(i);
}


void factorize( ll n ) {
    int sqrtN = sqrt(n),cnt;
    for ( int i = 0; i < primes.size() && primes[i] <= sqrtN; i++ ) {
        cnt = 0;
        if ( n % primes[i] == 0 ) {
            while ( n % primes[i] == 0 ) {
                n /= primes[i];
                cnt++;
            }
            factors.push_back({primes[i],cnt});
            sqrtN = sqrt(n);
        }
    }
    if ( n != 1 ) factors.push_back({n,1});
}


int main () {
    ///freopen("input.txt","r",stdin);
    ///freopen("output.txt","w",stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    ll n,p;
    sieve(int(1e7));
    scanf("%lld%lld",&n,&p);
    factorize(p);
    ll ans = 1;
    for ( int i = 0; i < factors.size(); i++ ) {
        ///cout << factors[i].f << ' ' << factors[i].s << endl;
        ans *= power(factors[i].f,int(factors[i].s/n));
    }
    printf("%lld\n",ans);
    return 0;
}



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

int main() { /* ここに書く */
 
  int N;
  cin >> N;
  vector<bool>RW(N);
  
 char S;
  int R = 0;
  
  for(int i = 0; i<N ; i++){
    
    cin >> S;
    
    if(S == 'R'){
      RW.at(i) = 1;
      R++;
    }
    
  }
  
   bool b;
  int c;
  c=0;
  
  for(int i = 0; i<R ; i++){
    
    b = RW.at(i);
    if(b == 0){
      c++;
    }
    
  }

  cout << c << endl;
}

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

using namespace std;

typedef unsigned long long ull;

int main()
{
    //freopen("IN.txt","r",stdin);
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    ull n;
    cin>>n;
    ull sum=0;
    for(ull i=1;i<=n;i++){
        if(i%3!=0 && i%5!=0){
            sum+=i;
        }
    }
    cout<<sum;
    return 0;
}

Measured memory_bytes: 3648
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
# define m 1000000007
int main() {
	
	ios_base::sync_with_stdio(false); 
    cin.tie(NULL); 
    cout.tie(NULL);
	
	ll n;
	cin>>n;
	ll a[n];
	ll sum=0;
	for(ll i=0;i<n;i++)
	{
	    cin>>a[i];
	    sum+=a[i];
	}
	
	ll ans=0;
	for(ll i=0;i<n;i++)
	{
	    sum-=a[i];
	    ans+=(((sum%m)*(a[i]%m))+m)%m;
	    ans=ans%m;
	}
	cout<<ans<<endl;
	
	return 0;
}


Measured memory_bytes: 5212
import Control.Monad
import Control.Monad.Primitive (PrimState)
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

solve :: MV.MVector (PrimState IO) Int -> MV.MVector (PrimState IO) Bool -> Int -> Int -> IO (Int, Int)
solve mva mvb i count = do
    next <- MV.read mva (i - 1)
    if next == 2
        then return (next, count)
        else do
            b <- MV.read mvb (next - 1)
            if b
                then return (next, count)
                else do
                    MV.write mvb (next - 1) True
                    solve mva mvb next (count + 1)
main :: IO ()
main = do
    n <- fst . fromJust . B.readInt <$> B.getLine
    mva <- MV.replicate 100000 0 :: IO (MV.MVector (PrimState IO) Int)
    mvb <- MV.replicate 100000 False :: IO (MV.MVector (PrimState IO) Bool)
    forM_ [0..(n - 1)] $ \i -> do
        a <- fst . fromJust . B.readInt <$> B.getLine
        MV.write mva i a
    (next, count) <- solve mva mvb 1 1
    print $ if next == 2 then count else -1


Measured memory_bytes: 1916
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <set> 
#include <map>
#include <bitset>
#include <cctype>
#include <cmath>
using namespace std;
#define REP(i,n) for(int i=0; i<(n); ++i)
#define FOR(i, a, b) for(int i=(a); i<(b); ++i)
typedef long long ll;
const int INF = 100100100;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;

int main () {

    int n; cin >>n;
    vector<string> s(n); REP (i,n) cin >> s[i];
    int m; cin >> m;
    vector<string> t(m); REP (i,m) cin >> t[i];

    int res = 0;
    for (int i = 0; i < n; i++) {
        int this_res = 0;
        string this_s = s[i];
        for (int j = 0; j < n; j++) {
            if(s[j] == this_s) {
                this_res += 1;
            } 
        }
        for (int j = 0; j < m; j++) {
            if(t[j] == this_s) {
                this_res -= 1;
            } 
        }
        res = max(res, max(this_res, 0));
    }

    cout << res << endl;

    return 0;
}



Measured memory_bytes: 256
#include<stdio.h>
#define MAX 250
#define NIL -1
typedef struct node{
  int leftid;
  int rightid;
  int left;
  int right;
  int key;
  int id;
  int p;
  int pid;

}Node;
Node node[MAX+1];
int main(){
  int n,i,num,l,tmp;
  scanf("%d",&n);
  for(i=1;i<=n;i++){
    node[i].left=NIL;
    node[i].right=NIL;
    node[i].leftid=NIL;
    node[i].rightid=NIL;
    node[i].key=NIL;
    node[i].id=NIL;
    node[i].p=NIL;
    node[i].pid=NIL;
  }
  for(i=1;i<=n;i++){
    scanf("%d",&num);
    if(i==1){
      node[i].key=num;
      node[i].id=i;
      tmp=node[i].id;
    }
   else if(node[tmp].leftid==NIL){
     node[i].key=num;
     node[tmp].left=num;
     node[tmp].leftid=i;
     node[i].p=node[i/2].key;
     node[i].pid=tmp;
    }
   else if(node[tmp].rightid==NIL){
     node[i].key=num;
     node[tmp].right=num;
     node[tmp].rightid=i;
     node[i].p=node[i/2].key;
     node[i].pid=tmp;
     tmp++;
   }
  }
  for(i=1;i<=n;i++){
    printf("node %d: key = %d, ",i,node[i].key);
    
  if(node[i].pid!=NIL){
    if(node[i].leftid==NIL){
      printf("parent key = %d, \n",node[i].p);
    }
    else{
      printf("parent key = %d, ",node[i].p);
    }
  }
  if(node[i].leftid!=NIL){
    if(node[i].rightid==NIL){
      printf("left key = %d, \n",node[i].left);
    }
    else printf("left key = %d, ",node[i].left);
  }
   if(node[i].rightid!=NIL){
    printf("right key = %d, \n",node[i].right);
  }
  }
  return 0;
}



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

int main(){
    int N, M;
    cin >> N >> M;

    vector<int> A(M,0);
    vector<int> B(M,0);
    
    for(int i=0; i < M; i++){
        cin >> A.at(i) >> B.at(i);
    }

    vector<int> C(N,0);

    for(int i=0; i < M; i++){
        for(int j=0; j < N; j++){
            if(A.at(i) == j+1){
                C.at(j) = C.at(j) + 1;
            }
            else if(B.at(i) == j+1){
                C.at(j) = C.at(j) + 1;
            }
        }
    }

    for(int k=0; k < N; k++){
        cout << C.at(k) << endl;
    } 

}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define all(c) (c).begin(),(c).end()
#define pb push_back
#define dbg(...) do{cerr<<__LINE__<<": ";dbgprint(#__VA_ARGS__, __VA_ARGS__);}while(0);

using namespace std;

namespace std{template<class S,class T>struct hash<pair<S,T>>{size_t operator()(const pair<S,T>&p)const{return ((size_t)1e9+7)*hash<S>()(p.first)+hash<T>()(p.second);}};template<class T>struct hash<vector<T>>{size_t operator()(const vector<T> &v)const{size_t h=0;for(auto i : v)h=h*((size_t)1e9+7)+hash<T>()(i)+1;return h;}};}
template<class T>ostream& operator<<(ostream &os, const vector<T> &v){os<<"[ ";rep(i,v.size())os<<v[i]<<(i==v.size()-1?" ]":", ");return os;}template<class T>ostream& operator<<(ostream &os,const set<T> &v){os<<"{ "; for(const auto &i:v)os<<i<<", ";return os<<"}";}
template<class T,class U>ostream& operator<<(ostream &os,const map<T,U> &v){os<<"{";for(const auto &i:v)os<<" "<<i.first<<": "<<i.second<<",";return os<<"}";}template<class T,class U>ostream& operator<<(ostream &os,const pair<T,U> &p){return os<<"("<<p.first<<", "<<p.second<<")";}
void dbgprint(const string &fmt){cerr<<endl;}template<class H,class... T>void dbgprint(const string &fmt,const H &h,const T&... r){cerr<<fmt.substr(0,fmt.find(","))<<"= "<<h<<" ";dbgprint(fmt.substr(fmt.find(",")+1),r...);}
typedef long long ll;typedef vector<int> vi;typedef pair<int,int> pi;const int inf = (int)1e9;const double INF = 1e12, EPS = 1e-9;

vector<vi> e;
int rec(int c){
	vi v;
	int res = 0;
	for(int i : e[c]) v.pb(rec(i));
	sort(all(v), greater<int>());
	rep(i, v.size()) res = max(res, v[i] + i + 1);
	return res;
}
int main(){
	cin.tie(0); cin.sync_with_stdio(0);
	int n; cin >> n;
	e.resize(n);
	for(int i = 1; i < n; i++){
		int x; cin >> x; x--;
		e[x].pb(i);
	}
	cout << rec(0) << endl;
	
	return 0;
}

Measured memory_bytes: 13568
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<vector>
#include<climits>
#include<map>
#include<string>
#include<functional>
#include<iomanip>
#include<deque>
#include<random>
#include<set>

using namespace std;
typedef long long ll;
typedef double lldo;
#define mp make_pair
#define pub push_back
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define sz(x) int(x.size())
ll gcd(ll a, ll b) { if (a % b == 0) { return b; } else  return gcd(b, a % b); }
ll lcm(ll a, ll b) { if (a == 0) { return b; }return a / gcd(a, b) * b; }
template<class T>ll LBI(vector<T>& ar, T in) { return lower_bound(ar.begin(), ar.end(), in) - ar.begin(); }
template<class T>ll UBI(vector<T>& ar, T in) { return upper_bound(ar.begin(), ar.end(), in) - ar.begin(); }

ll N, P, idx[100001] = {}, ans = 0;
set<ll> s;

int main() {
	cin >> N;
	for (int i = 1; i <= N; i++) {
		cin >> P;
		idx[P] = i;
	}
	for (int i = N; i > 0; i--) {
		vector<ll>l(2, 0), r(2, N + 1);
		s.insert(idx[i]);
		auto it = s.find(idx[i]);
		rep(j, 2) {
			if (it == s.begin())break;
			it--;
			l[j] = *it;
		}
		it = s.find(idx[i]);
		rep(j, 2) {
			it++;
			if (it == s.end())break;
			r[j] = *it;
		}
		ans += i * ((l[0] - l[1]) * (r[0] - idx[i]) + (idx[i] - l[0]) * (r[1] - r[0]));
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 5760
using System;
using System.Collections.Generic;
using System.Linq;
using static Input;

public class Prog
{
    private const int INF = 1000000007;
    public struct Pair { public int x, y; public Pair(int x, int y) { this.x = x; this.y = y; } }
    public static void Solve()
    {
        int N = NextInt();
        int D = NextInt();
        int[,] X = new int[N, D];
        for (int i = 0; i < N; i++)
            for (int j = 0; j < D; j++) X[i, j] = NextInt();

        int ans = 0;
        for (int i = 0; i < N; i++)
            for (int j = i + 1; j < N; j++)
            {
                double num = 0;
                for (int k = 0; k < D; k++) { num += Math.Pow(Math.Abs(X[i, k] - X[j, k]), 2); }
                if (Math.Sqrt(num) % 1 == 0) ans++;
            }
        Console.WriteLine(ans);
    }
    public static void Main()
    {
        var sw = new System.IO.StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        Console.SetOut(sw);
        Solve();
        Console.Out.Flush();
    }
}

public class Input
{
    private static Queue<string> q = new Queue<string>();
    private static void Confirm() { if (q.Count == 0) foreach (var s in Console.ReadLine().Split(' ')) q.Enqueue(s); }
    public static int NextInt() { Confirm(); return int.Parse(q.Dequeue()); }
    public static long NextLong() { Confirm(); return long.Parse(q.Dequeue()); }
    public static char NextChar() { Confirm(); return char.Parse(q.Dequeue()); }
    public static string NextString() { Confirm(); return q.Dequeue(); }
    public static double NextDouble() { Confirm(); return double.Parse(q.Dequeue()); }
    public static int[] LineInt() { return Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); }
    public static long[] LineLong() { return Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); }
    public static string[] LineString() { return Console.ReadLine().Split(' ').ToArray(); }
    public static double[] LineDouble() { return Console.ReadLine().Split(' ').Select(double.Parse).ToArray(); }
}


Measured memory_bytes: 11348
#include<stdio.h>
int main(void){
    int N,M,C,count=0;
    scanf("%d%d%d",&N,&M,&C);
    int B[M],A[N][M];
    for(int i=0;i<M;i++){
        scanf("%d",&B[i]);
    }
    for(int i=0;i<N;i++){
        int mix=0;
        for(int j=0;j<M;j++){
            scanf("%d",&A[i][j]);
            mix+=A[i][j]*B[j];
        }
        if(mix+C>0)
            count++;
    }
    printf("%d\n",count);
    return 0;
}


Measured memory_bytes: 128
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {

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

		int n = in.nextInt();

		List<Long> list = new ArrayList<>();
		for (int i = 0; i < n; i++) {
			list.add(in.nextLong());
		}
		in.close();
		
		Collections.sort(list);
		long[] sum = new long[n];
		
		sum[0] = list.get(0);
		for (int i = 1; i < n; i++) {
			sum[i] = sum[i - 1] + list.get(i);
		}
		
		int start = 0;
		for (int i = 1; i < sum.length; i++) {
//			System.out.println(list.get(i) + ">" + (long)2 * sum[i - 1]);
			
			if(list.get(i) > (long)2 * sum[i - 1]) {
				start = i;
			}
		}
//		System.out.println(Long.MAX_VALUE);
		System.out.println(n - start);
	}

}


Measured memory_bytes: 62400
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    int a, b;

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

    void run() {
        FastReader sc = new FastReader();
        a = sc.nextInt();
        b = sc.nextInt();
        solve();
    }

    void solve() {
        System.out.println(Math.max(a + b, Math.max(a - b, a * b)));
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
}


Measured memory_bytes: 21076
#include <iostream>

int main(){
    int x=1;
    int ncase = 1;

    while(x!=0){
        std::cin >> x;
        if(x==0){
            break;
        }
        std::cout << "Case " << ncase << ": " << x << std::endl;
        ncase += 1;
    }
}



Measured memory_bytes: 3120
#include<stdio.h>
#define SIZE 100
int stack[SIZE];
int n=0;

void push(int x){
    stack[n]=x;
    n++;
}
int pop(){
    n--;
    return stack[n];
}

int main(void){
    char c[1000000];
    int x,a,b;
    
    while(scanf("%s",c)!=EOF){
      if(isdigit(c[0])){
	x=atoi(c);
	push(x);
      }else if(c[0]=='+'){
	push(pop()+pop());
      }else if(c[0]=='-'){
	b=pop();
	a=pop();
	push(a-b);
      }else if(c[0]=='*'){
	push(pop()*pop());
      }
    }
    printf("%d\n",pop());
    return 0;
}


Measured memory_bytes: 2044