akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>

using namespace std;

typedef boost::multiprecision::cpp_int ll;
typedef pair<ll, ll> P;
typedef vector<ll> vl;
typedef vector<vl> vvl;
template<typename T> using pq = priority_queue<T>;
template<typename T> using minpq = priority_queue<T, vector<T>, greater<T>>;
template<typename T, typename K> using ump = unordered_map<T, K>;
const ll dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
const ll mod = 1000000007;
const ll inf = ll(1e9);
const int e5 = (1e5);
const ll ll_inf = ll(1e9) * ll(1e9);

#define rep(i, n) for(ll i = 0; i < (ll)(n); i++)
#define repr(i, n) for(ll i = n - 1; i >= 0; i--)
#define repone(i, n) for(ll i = 1; i <= (ll)(n); i++)
#define each(i, mp) for(auto& i:mp)
#define eb emplace_back
#define F first
#define S second
#define all(obj) (obj).begin(), (obj).end()

template<class T>
void dump_debug(T list) {
#ifdef MY_DEBUG
    each(e, list) cout << e << " ";
    printf("\n");
#endif
}

/* ------------- ANSWER ------------- */
/* ---------------------------------- */
vector<ll> G[2 * e5];
vector<ll> ans(2 * e5);
unordered_map<int, ll> pl;
vector<bool> seen(2 * e5);

void dfs(int now, ll value) {
    seen[now] = true;
    ans[now] = value;
    each(e, G[now]) {
        if (!seen[int(e)]) {
            dfs(int(e), value + pl[int(e)]);
        }
    }
}

int main() {
#ifdef MY_DEBUG
    while (true) {
#endif
        ll n, q;
        cin >> n >> q;
        rep(i, n - 1) {
            int a, b;
            cin >> a >> b;
            a--, b--;
            G[a].eb(b);
            G[b].eb(a);
        }

        rep(i, q) {
            ll p, x;
            cin >> p >> x;
            p--;
            pl[int(p)] += x;
        }
        dfs(0, pl[0]);

        rep(i, n) cout << ans[int(i)] << " ";

#ifdef MY_DEBUG
    }
#endif
    return 0;
}

Measured memory_bytes: 107464
#include<iostream>
#include<algorithm>
#include<climits>
#include<vector>
#include<utility>//pair
#include<cmath>//abs,sqrt
#include<cstring>
#include<map>
#define rep(i,n) for(int i=0;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define prin(arg) std::cout<<arg<<"\n"
#define prin2(arg1,arg2) std::cout<<arg1<<" "<<arg2<<"\n"
#define fill(arg,n) memset(arg,n,sizeof(arg))
using std::cin;
typedef long long ll;
const int INF=1e+9;
const ll INFLL=1e+17;
int N,C;
int D[40][40];
int c[510][510];
int num[4][40];
int disc[4][40];
void count(){
  fill(num,0);
  rep(i,N){
    rep(j,N){
      if((i+j)%3==0) num[0][c[i][j]]++;
      else if((i+j)%3==1) num[1][c[i][j]]++;
      else num[2][c[i][j]]++;
    }
  }
}
void makedis(){
  rep(i,3){
    rep(j,C){
      disc[i][j]=0;
      rep(k,C){
	disc[i][j]+=num[i][k]*D[k][j];
      }
    }
  }
}

int solve(){
  count();
  makedis();
  int res=INF;
  int comb=(1<<3)-1;
  while(comb<(1<<C)){
    int z[3],k=0;
    rep(i,C){
      if(comb>>i&1){
	z[k]=i;
	k++;
      }
    }
    rep(i,6){
      int temp=0;
      rep(j,3){
	temp+=disc[j][z[j]];
      }
      res=std::min(res,temp);
      std::next_permutation(z,z+3);
    }
    int x=comb&-comb;
    int y=comb+x;
    comb=((comb&~y)/x>>1)|y;
  }
  return res;
}


int main(){
  cin>>N>>C;
  rep(i,C){
    rep(j,C){
      cin>>D[i][j];
    }
  }
  rep(i,N){
    rep(j,N){
      cin>>c[i][j];
      c[i][j]--;
    }
  }
  prin(solve());
  return 0;
}


Measured memory_bytes: 1280
#include<bits/stdc++.h>
using namespace std;
long long X, Y;
int i;
int main(){
  cin >> X >> Y;

  long long num = X, answer = 1;
  while(1){
    if(num * 2 <= Y){
        num *= 2;
        answer++;
    }else break;

  }

  cout << answer << endl;
  return 0;
}


Measured memory_bytes: 256
#[allow(unused_imports)]
use std::char::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;

#[allow(unused_macros)]
macro_rules! debug {($($a:expr),*) => {println!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);}}
#[allow(unused_macros)]
macro_rules! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; let mut next = || { iter . next ( ) . unwrap ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let mut bytes = std :: io :: Read :: bytes ( std :: io :: BufReader :: new ( stdin . lock ( ) ) ) ; let mut next = move || -> String { bytes . by_ref ( ) . map ( | r | r . unwrap ( ) as char ) . skip_while ( | c | c . is_whitespace ( ) ) . take_while ( | c |! c . is_whitespace ( ) ) . collect ( ) } ; input_inner ! { next , $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules! input_inner { ( $ next : expr ) => { } ; ( $ next : expr , ) => { } ; ( $ next : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ next , $ t ) ; input_inner ! { $ next $ ( $ r ) * } } ; }
#[allow(unused_macros)]
macro_rules! read_value { ( $ next : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ next , $ t ) ) ,* ) } ; ( $ next : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ next , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ next : expr , chars ) => { read_value ! ( $ next , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ next : expr , usize1 ) => { read_value ! ( $ next , usize ) - 1 } ; ( $ next : expr , $ t : ty ) => { $ next ( ) . parse ::<$ t > ( ) . expect ( "Parse error" ) } ; }

#[derive(PartialEq, PartialOrd)]
pub struct Total<T>(pub T);
impl<T: PartialEq> Eq for Total<T> {}
impl<T: PartialOrd> Ord for Total<T> { fn cmp(&self, other: &Total<T>) -> std::cmp::Ordering { self.0.partial_cmp(&other.0).unwrap() }}

#[allow(dead_code)]
const MAX:usize = 100006;
#[allow(dead_code)]
const INF_U32:u32 = 1 << 31;
#[allow(dead_code)]
const INF_I32:i32 = 1 << 30;
#[allow(dead_code)]
const INF_U64:u64 = 1 << 63;
#[allow(dead_code)]
const INF_I64:i64 = 1 << 62;


fn main() {
    input!{n:usize, a:[i64;n]};
    let mut f = vec![false; n];
    f[0] = true;
    let mut idx:usize = 0;
    let mut cnt:i64 = 1;
    loop {
        if a[idx] == 2 {
            println!("{}", cnt);
            return ();
        }
        idx = (a[idx] - 1) as usize;
        cnt += 1;
        if f[idx] {
            println!("-1");
            return ();
        }
        f[idx] = true;
    }
}


Measured memory_bytes: 4352
#include<iostream>
using namespace std;
int main(void)
{
  	ios::sync_with_stdio(false);
  	cin.tie(NULL);
  	cout.tie(NULL);
  	int k,x;
  	cin >> k >> x;
  	for(int i=x-k+1;i<=x+k-1;i++)
      	cout << i << ' ';
  	return 0;
}

Measured memory_bytes: 256
/*
    Author - Param Kothari
    Ah shit, here we go again
*/

#include <bits/stdc++.h>
 
using namespace std;

#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define pb push_back
#define mk make_pair

typedef long long ll;
typedef long double ld;

void solve(){
    int x;
    cin >> x;
    cout << (x >= 30 ? "Yes\n" : "No\n");
    return;
}

int main(){
    IOS;
    int t = 1;
    // cin >> t;
    for(int i = 1; i <= t; i++){
        solve();
    }
    return 0;
}

Measured memory_bytes: 3652
import java.util.*;

public class Main {
    public static void main (String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] counter = new int[100];
        int maxCnt = 0;
        
        for (int i = 0; i < counter.length; i++) {
            counter[i] = 0;
        }
        
        while (scanner.hasNext()) {
            int n = scanner.nextInt() - 1;
            counter[n]++;
            if (counter[n] > maxCnt) {
                maxCnt = counter[n];
            } 
        }
        
        for (int i = 0; i < counter.length; i++) {
            if (counter[i] == maxCnt) {
                System.out.println(i+1);
            }
        }
    }
}

Measured memory_bytes: 16296
#include<iostream>
using namespace std;
const int MAXN=101;
long long f[MAXN],X;
int main(){
	cin>>X;
	f[0]=2;
	for(int i=1;i<=X;i++) f[i]=f[i-1]*2+2;
	cout<<f[X]<<endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define fr first
#define sc second

using namespace std;

int u[150], dif;
pair<int, char>mx;
pair<int, char>mx2;
int sum;
main()
{
    string s, s1 = "";
    cin >> s;
    mx.fr = 100005 * -1;
    mx2.fr = 100005 * -1;
    for (int i = 0; i < s.size(); i++)
        u[s[i]]++;
    for (int i = 95; i <= 130; i++)
    {
        if (mx.fr < u[i])
        {
            mx.fr = u[i];
            mx.sc = (char)i;
        }
        else
        {
            if (mx2.fr < u[i])
            {
                mx2.fr = u[i];
                mx2.sc = (char)i;
            }
        }
    }
    s1 = s;
    sort(s1.begin(), s1.end());
    for (int i = 0; i < s1.size() - 1; i++)
    {
        if (s1[i] != s1[i + 1])dif++;
    }
    dif++;
    if (dif == 2 && mx.fr != mx2.fr)
    {
        cout << "NO";
        return 0;
    }
    for (int i = 0; i < s.size(); i++)
    {
        if (u[s[i]] && s[i] != mx.sc && s[i] != mx2.sc)
        {
            sum += u[s[i]];
            u[s[i]] = 0;
        }
    }
    if (mx.fr <= sum + 1 && mx.fr - mx2.fr < 2)
    {
        cout << "YES";
    }
    else
    {
        cout << "NO";
    }

}




Measured memory_bytes: 512
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
printV = lambda x: print(*x, sep="\n")
printH = lambda x: print(" ".join(map(str,x)))
def IS(): return sys.stdin.readline()[:-1]
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LII(rows_number): return [II() for _ in range(rows_number)]
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]

def main():
	A = []
	S = [[False,False,False] for i in range(3)]
	for i in range(3):
		a=LI()
		A.append(a)
	N = II()
	for _ in range(N):
		b = II()
		for i in range(3):
			for j in range(3):
				if(A[i][j]==b):
					S[i][j]=True
	if((S[0][2]==S[1][2]==S[2][2]==True) or(S[0][1]==S[1][1]==S[2][1]==True) or(S[0][0]==S[1][0]==S[2][0]==True) or(S[0][0]==S[0][1]==S[0][2]==True) or (S[1][0]==S[1][1]==S[1][2]==True) or (S[2][0]==S[2][1]==S[2][2]==True) or (S[0][0]==S[1][1]==S[2][2]==True) or (S[2][0]==S[1][1]==S[0][2]==True)):
		print("Yes")
	else:
		print("No")

if __name__ == '__main__':
	main()

Measured memory_bytes: 3192
#pragma GCC optimize("O3")
#include<bits/stdc++.h>

#define ll long long
#define rep(A,B,C) for(A=B;A<C;++A)
#define pii pair<int,int>
#define pll pair<ll,ll>

using namespace std;

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

/////////////////////////////////////////////////////
#define vv vector


ll T;
ll N;
char X[202020];
ll mk[202020];
ll ans[202020];
ll i, j, k;


ll calc(ll a){
    ll r = 0;
    while(a){
        ll a2 = a;
        ll b = 0;
        while(a2){
            if(a2&1){
                ++b;
            }
            a2 >>= 1;
        }
        a = a % b;
        ++r;
    }
    return r;
}

int main(){
    scanf("%lld%s", &N,X);
    j = 0;
    rep(i,0,N){
        mk[i] = 1 + calc(i);
        if(X[i]=='1'){
            ++j;
        }
    }
    ll a = 0, a2 = 1, b = 0, b2 = 1;
    rep(i,0,N){
        if(j>1)
        (a *= 2) %= (j - 1);
        (b *= 2) %= (j + 1);
        if(X[i]=='1'){
            ++a;
            ++b;
        }
    }
    //printf("%lld %llda\n", a, b);
    rep(i,0,N){
        ll ii = N - 1 - i;
        if(X[ii]=='1'){
            if(j==1){
                ans[ii] = 0;
            }else{
                ll c = (a - a2 + j - 1) % (j - 1);
                //printf("a%lld\n", c);
                ans[ii] = mk[(a - a2 + j - 1) % (j - 1)];
            }
        }else{
            ll c = (b + b2) % (j + 1);
            //printf("b%lld\n", c);
            ans[ii] = mk[(b + b2) % (j + 1)];
        }
        if(j>1)
            a2 = a2 * 2 % (j - 1);
        b2 = b2 * 2 % (j + 1);
    }
    rep(i,0,N){
        printf("%lld\n", ans[i]);
    }
    
    return 0;
}

Measured memory_bytes: 7084
#include <iostream>

using namespace std;

int main() {
	int a, b, c, x, y;
	cin >> a >> b >> c >> x >> y;

	int c2 = 2 * c;
	if (a + b < c2) c2 = a + b;
	if (a > c2) a = c2;
	if (b > c2) b = c2;

	int cc = min(x, y);

	cout << cc * c2 + (x - cc) * a + (y - cc) * b << endl;
	return 0;
}


Measured memory_bytes: 256
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n)]
        self.rank = [0] * (n)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

n,m,k=map(int,input().split())
friends_cand = UnionFind(n)
not_cand = [0 for i in range(n)]

for i in range(m):
    a,b = map(int, input().split())
    a, b = a-1, b-1
    friends_cand.union(a,b)
    not_cand[a] +=1
    not_cand[b] +=1
for i in range(k):
    c,d = map(int, input().split())
    c, d = c-1, d-1
    if friends_cand.find(c) == friends_cand.find(d):
        not_cand[c] +=1
        not_cand[d] +=1

size = [0 for i in range(n)]
for i in range(n):
    size[friends_cand.find(i)]+=1

ans = []
for i in range(n):
    ans.append(size[friends_cand.find(i)] - not_cand[i] - 1)
print(*ans)

Measured memory_bytes: 15704
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
long long n,a[200005],med,ans;
main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        a[i]-=i;
    }
    sort(a+1,a+n+1);
    med=a[(n+1)/2];
    for(int i=1;i<=n;i++){
        ans+=abs(a[i]-med);
    }
    cout<<ans<<endl;
}

Measured memory_bytes: 1792
A, B, C  = map(int, input().split())
K = int(input())
flg = 0
for i in range(K):
  if B > A:
    if C > B or 2*C > B:
      flg = 1
    else:
        C = 2*C
  else:
    B = 2*B
    continue
if flg:
    print('Yes')
else:
    print('No')

Measured memory_bytes: 9148
#include <iostream>
#include <cmath>

using std::cin;

constexpr double PI = 3.1415926535;

class Point {
public:
    double x;
    double y;

    Point(double xx = 0.0, double yy = 0.0)
        : x(xx), y(yy) {}
};

void calcKochCurvePoint(int n, Point& p1, Point& p2);
void printPoint(Point& p);

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

    Point p1(0.0, 0.0);
    Point p2(100.0, 0.0);

    printPoint(p1);
    calcKochCurvePoint(n, p1, p2);
    printPoint(p2);

    return 0;
}

void calcKochCurvePoint(int n, Point& p1, Point& p2)
{
    if (n == 0) {
        return ;
    }

    Point s, t, u;
    s.x = (2 * p1.x + p2.x) / 3;
    s.y = (2 * p1.y + p2.y) / 3;
    t.x = (p1.x + 2 * p2.x) / 3;
    t.y = (p1.y + 2 * p2.y) / 3;
    u.x = s.x + (t.x - s.x) * cos(PI / 3) - (t.y - s.y) * sin(PI / 3);
    u.y = s.y + (t.x - s.x) * sin(PI / 3) + (t.y - s.y) * cos(PI / 3);

    calcKochCurvePoint(n - 1, p1, s);
    printPoint(s);
    calcKochCurvePoint(n - 1, s, u);
    printPoint(u);
    calcKochCurvePoint(n - 1, u, t);
    printPoint(t);
    calcKochCurvePoint(n - 1, t, p2);
}

void printPoint(Point& p)
{
    std::cout << p.x << " " << p.y << std::endl;
}

Measured memory_bytes: 1236
program main
  implicit none
  integer :: n, i, l, res
  character(10) :: s
  read (*, *) n
  res = 0
  do i = 1, n
    write (s, "(i0)") i
    l = len(trim(s))
    res = res + mod(l, 2)
  end do
  write (*, "(i0)") res
end program main


Measured memory_bytes: 384
import java.util.Scanner;
class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int x = scan.nextInt();
        int y = scan.nextInt();
        int ans = Integer.MAX_VALUE;

        for(int i=-1;i<=1;i+=2){
            for(int j=-1;j<=1;j+=2){
                int X = x*i;
                int Y = y*j;
                if(X>Y)continue;
                ans = Math.min(ans,Y-X +(-i+1)/2 +(-j+1)/2);
            }
        }
        System.out.println(ans);
    }
}

Measured memory_bytes: 23892
macro_rules! debug {
    ( $x:expr ) => {
        if cfg!(debug_assertions) {
            println!("{}:{} {} = {:?}", line!(), column!(), stringify!($x), $x);
        }
    }
}

fn main() {
    let stdin = std::io::stdin();
    let mut stdin = my::io::InputReader::new(stdin.lock());

    const MOD: u64 = 1_000_000_007;
    let N: usize = stdin.read();
    let s: String = stdin.read();
    let s = s.as_bytes();

    let mut dp = vec![vec![0; N]; N];
    dp[0][0] = 1;

    for i in 1..N {
        if s[i - 1] == b'<' {
            dp[i][0] = 0;
            for j in 1..i + 1 {
                dp[i][j] = (dp[i][j - 1] + dp[i - 1][j - 1]) % MOD;
                //println!("dp[{}][{}] = {}", i, j, dp[i][j]);
            }
        } else if s[i - 1] == b'>' {
            dp[i][i] = 0;
            for j in (0..i).rev() {
                dp[i][j] = (dp[i][j + 1] + dp[i - 1][j]) % MOD;
                //println!("dp[{}][{}] = {}", i, j, dp[i][j]);
            }
        }
    }

    let mut result = 0;
    for i in 0..N {
        result += dp[N - 1][i];
    }
    result %= MOD;

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

mod my {
    pub mod io {
        use std::io::{BufRead, ErrorKind, Result};
        use std::str::{FromStr, from_utf8};
        use std::fmt::Debug;

        pub fn read_word<R: BufRead>(r: &mut R, buf: &mut Vec<u8>)
                                              -> Result<usize> {
            let mut read = 0;
            loop {
                let (done, used) = {
                    let available = match r.fill_buf() {
                        Ok(n) => n,
                        Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                        Err(e) => return Err(e)
                    };
                    match available.iter().position(|&x| x == b'\n' || x == b' ') {
                        Some(i) => {
                            buf.extend_from_slice(&available[..i]);
                            (true, i + 1)
                        }
                        None => {
                            buf.extend_from_slice(available);
                            (false, available.len())
                        }
                    }
                };
                r.consume(used);
                read += used;
                if done || used == 0 {
                    return Ok(read);
                }
            }
        }

        pub struct InputReader<R: BufRead> {
            reader: R,
            buf: Vec<u8>,
        }

        impl<R: BufRead> InputReader<R> {
            pub fn new(reader: R) -> InputReader<R> {
                InputReader {
                    reader: reader,
                    buf: Vec::<u8>::new(),
                }
            }

            pub fn read_word(&mut self) {
                read_word(&mut self.reader, &mut self.buf);
            }
            
            pub fn read<T>(&mut self) -> T
                where T: FromStr,
                      T::Err: Debug
            {
                self.buf.clear();
                self.read_word();
                from_utf8(&self.buf).unwrap().trim().parse().unwrap()
            }
        }
    }
}



Measured memory_bytes: 90364
while 1:
    W,H = map(int,raw_input().split())
    if W == 0: break
    C = [list(raw_input()) for _ in xrange(H)]
    
    dp = [["0"]*W for _ in xrange(H)]
    ans = 0
    for h in xrange(H):
        for w in xrange(W):
            if C[h][w].isdigit():
                dp[h][w] = str(max(int(dp[h][w]),int(C[h][w])))
                if w > 0: dp[h][w] = str(max(int(dp[h][w]),int(dp[h][w-1]+C[h][w])))
                if h > 0: dp[h][w] = str(max(int(dp[h][w]),int(dp[h-1][w]+C[h][w])))
                ans = max(ans, int(dp[h][w]))
    print ans

Measured memory_bytes: 4360
import java.util.*;
import java.io.*;
import java.awt.geom.*;
import java.math.*;

public class Main {

	static final Scanner in = new Scanner(System.in);
	static final PrintWriter out = new PrintWriter(System.out,false);
	static boolean debug = false;

	static void solve() {
		String s = in.next();
		out.println(s.substring(0, 4)+" "+s.substring(4));
	}

	public static void main(String[] args) {
		debug = args.length > 0;
		long start = System.nanoTime();

		solve();
		out.flush();

		long end = System.nanoTime();
		dump((end - start) / 1000000 + " ms");
		in.close();
		out.close();
	}

	static void dump(Object... o) { if (debug) System.err.println(Arrays.deepToString(o)); }
}

Measured memory_bytes: 10188
#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define im imag()
#define re real()
#define r(I, N) for(int I=0;I<N;I++)
#define f(I, A, B) for(int I=A;I<B;I++)
#define fd(I, A, B) for(int I=A;I>=B;I--)
#define ite(x) for(__typeof((x).begin()) it=(x).begin();it!=(x).end();it++)
#define sz(x) ((int)(x).size())
#define clr(x) memset(x, 0, sizeof(x))

typedef pair<int, int> pii;
typedef long long ll;
typedef long double ld;
typedef complex<ld> Point;
typedef Point Vector;

const ld pi = acos(-1.0);
const ld eps = 1e-12;

int N, M;
int r[20], a[20], b[20];

int main()
{
      cin >> N >> M;
      r(i, N) cin >> a[i], b[i] = a[i];
      r(i, M) cin >> r[i];

      /// Case 1 : 0

      int pt = 0, num = 0, ans1 = 0, ans2 = 0;

      bool flag1 = true;

      r(i, N)
      {
            f(j, i, i + r[pt])
            {
                  if(a[j] != num)
                  {
                        int rt = j;
                        while(a[rt] != num && rt < N) rt++;
                        if(rt >= N)
                        {
                              flag1 = false;
                              break;
                        }
                        swap(a[rt], a[j]);
                        ans1 += rt - j;
                  }
            }
            i += r[pt++] - 1;
            num = !num;
      }

      /// Case 2 : 1
      bool flag2 = true;
      num = 1;
      pt = 0;

      r(i, N)
      {
            f(j, i, i + r[pt])
            {
                  if(b[j] != num)
                  {
                        int rt = j;
                        while(b[rt] != num && rt < N) rt++;
                        if(rt >= N)
                        {
                              flag2 = false;
                              break;
                        }
                        swap(b[rt], b[j]);
                        ans2 += rt - j;
                  }
            }
            i += r[pt++] - 1;
            num = !num;
      }
      if(flag1 && !flag2) cout << ans1 << endl;
      else if(!flag1 && flag2) cout << ans2<< endl;
      else cout << min(ans1, ans2) << endl;
      return 0;
}

Measured memory_bytes: 1164
def resolve():
    N, M = map(int, input().split())
    A = list(map(int, input().split()))

    if M > len(A):
        print('No')
        return

    A.sort(reverse=True)
    total = sum(A)

    for i in range(M):
        if (A[i] < total * (1 / (4 * M))):
            print('No')
            return

    print('Yes')


resolve()

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

using ll = long long;
using Vi = vector<int>;
using Vl = vector<ll>;
using Pii = pair<int, int>;
using Pll = pair<ll, ll>;

constexpr int I_INF = numeric_limits<int>::max();
constexpr ll L_INF = numeric_limits<ll>::max();

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

ll binom(ll n, ll k) {
    ll p = 1, q = 1;
    for (ll i = 0; i < k; i++) {
        p *= n - k + i + 1;
        q *= i + 1;
        ll g = gcd(p, q);
        p /= g;
        q /= g;
    }
    return p / q;
}

void solve() {
    ll N, A, B;
    cin >> N >> A >> B;
    Vl V(N), cum(N + 1);
    for (ll i = 0; i < N; i++) {
        cin >> V[i];
    }
    sort(V.begin(), V.end(), greater<ll>());
    for (ll i = 0; i < N; i++) {
        cum[i + 1] = cum[i] + V[i];
    }
    ll s_mx = -1, k_mx = 1;
    ll val = 0;
    for (ll i = A; i <= B; i++) {
        ll s = cum[i];

        if (i * s_mx > k_mx * s) {
            continue;
        }

        if (i * s_mx < k_mx * s) {
            s_mx = s;
            k_mx = i;
            val = 0;
        }

        ll a = V[i - 1];
        ll cnt1 = 0, cnt2 = 0;
        for (ll j = 0; j < N; j++) {
            if (V[j] == a) {
                if (j < i) {
                    ++cnt1;
                }
                else {
                    ++cnt2;
                }
            }
        }

        val += binom(cnt1 + cnt2, cnt1);
    }

    cout << setprecision(20) << (double)s_mx / k_mx << "\n";
    cout << val << "\n";
}

//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

int main() {
#ifdef FASTIO
    cin.tie(0), cout.tie(0);
    ios::sync_with_stdio(false);
#endif
#ifdef FILEINPUT
    ifstream ifs("./in_out/input.txt");
    cin.rdbuf(ifs.rdbuf());
#endif
#ifdef FILEOUTPUT
    ofstream ofs("./in_out/output.txt");
    cout.rdbuf(ofs.rdbuf());
#endif
    solve();
    cout << flush;
    return 0;
}

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

int main(){
    int A[3];
    cin >> A[0] >> A[1] >> A[2];
    int K;
    cin >> K;
    sort(A,A+3);
    for(int i=0;i<K;i++){
        A[2] = A[2] * 2;
    }
    int sum = 0;
    sum = A[0] + A[1] + A[2];
    cout << sum <<"\n";

    return 0;
}


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

int main(){
  vector<int> a(5);
  rep(i,5){
    cin>>a[i];
    if(a[i]==0) cout<<i+1<<endl;
  }
}

Measured memory_bytes: 3604
from collections import Counter,defaultdict
import sys,heapq,bisect,math,itertools,string,queue,datetime
mod = 10**9+7
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_str(): return list(sys.stdin.readline().split())

a,b = inpl()
if b == 1:
    print(0)
    quit()
b -= a
if b <= 0:
    print(1)
else:
    print(math.ceil(b/(a-1))+1)

Measured memory_bytes: 4204
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
#define INF LONG_LONG_MAX
#define pb push_back
#define mp make_pair
#define MAXN 1000009
#define MOD 1000000007
#define MAX(a,b) (((a)>(b))?(a):(b))
#define MIN(a,b) (((a)<(b))?(a):(b))
#define left(x) x<<1
#define right(x) (x<<1)|1
#define PI acos(-1.0)
using namespace std;
using namespace __gnu_pbds;

typedef long long ll;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef pair<ll,ll> ii;
typedef vector<ii> vii;
typedef map<string,ll> msi;
typedef set<ll> si;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> 
ordered_set;
typedef tree<ii,null_type,less<ii>,rb_tree_tag,tree_order_statistics_node_update> 
ordered_multiset;

ll solve(){
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;++i)
        cin>>a[i];
    sort(a,a+n);
    cout<<a[n-1]-a[0];
    return 0;
}

int main(){
    int T=1;
    //scanf("%d",&T);
    for(int i=1;i<=T;++i){
        solve();
    }
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
using namespace std;
long long f(long long n){
    return n*(n+1LL)/2LL;
}
int main(){
    string s,r;
    cin>>s;
    long long ans=0LL,c=1LL,m=0LL,bc=0LL;
    char b;
    for(long long i=1;i<s.size();i++){
        if(s[i-1]==s[i])c++;
        else {
            if(s[i]=='>'){
                bc=c;
            }
            else m+=min(c,bc);
            ans+=f(c);
            c=1LL;
        }
    }
    ans+=f(c);
    if(s[s.size()-1]=='>')m+=min(c,bc);
    cout<<ans-m<<endl;
    return 0;
}

Measured memory_bytes: 900
#include <cstdio>

int main(){
    int n,m;
    char suit,suits[4]={'S','H','C','D'};
    int cards[4][13] = {0};

    scanf("%d\n",&n);
    // printf("n:%d\n",n);
    for(int i = 0;i<n;i++){
        scanf("%c %d\n",&suit,&m);
        // printf("read:%c %d\n",suit,m);
        for(int j = 0; j< 4; j++){
            if(suit == suits[j])cards[j][m-1] = 1;
        }
    }
    for(int i = 0;i<4;i++){
        for(int j = 0;j<13;j++){
            if(!cards[i][j])printf("%c %d\n",suits[i],j+1);
        }
    }
    return 0;
}


Measured memory_bytes: 2716
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;

int main(){
    long n;
    cin >> n;
    long m = sqrt(n);
    cout << m*m << endl;
    return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main(int argc, char *argv[]) {
	int n, q;
	cin >> n >> q;
	string s;
	cin >> s;
	int l[q];
	int r[q];
	for (int i = 0; i < q; i++) {
		cin >> l[i] >> r[i];
	}
	
	int cash[n];
	cash[0] = 0;
	for (int i = 1; i < n; i++) {
		if (s[i-1] == 'A' && s[i] == 'C') {
			cash[i] = cash[i-1] + 1;
		} else {
			cash[i] = cash[i-1];
		}
	}
	for (int i = 0; i < q; i++) {
		int ans = cash[r[i]-1] - cash[l[i]-1];
		cout << ans << endl;
	}
}

Measured memory_bytes: 2176
# -*- coding: utf-8 -*-
# 
import math
import sys
import itertools
import numpy as np

# いっこ入力
n =int(input())

# 空白区切りの数列をリストに代入
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
max_mon = 0
if a[0] < b[0]:
    max_mon += a[0]
    b[0] = b[0] - a[0]
else:
    max_mon += b[0]
    b[0]=0
for i in range(1,n):
    if a[i] < b[i-1]:
        max_mon += a[i]
        b[i-1] = b[i-1] - a[i]
        a[i] = 0
    else:
        max_mon += b[i-1]
        a[i] = a[i] - b[i-1]
        b[i-1] = 0
    if a[i] < b[i]:
        max_mon += a[i]
        b[i] = b[i] - a[i]
        a[i] = 0
    else:
        max_mon += b[i]
        a[i] = a[i] - b[i]
        b[i] = 0
if a[n] < b[n-1]:
    max_mon += a[n]
    b[n-1] = b[n-1] - a[n]
    a[n] = 0
else:
    max_mon += b[n-1]
    a[n] = a[n] - b[n-1]
    b[n-1] = 0


print(max_mon)



Measured memory_bytes: 27300
#include <bits/stdc++.h>
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define RFOR(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define rep(i,n) FOR(i,0,(n))
#define REPS(i,n) FOR(i,1,(n)+1)
#define RREP(i,n) RFOR(i,0,(n))
#define ALL(x) (x).begin(),(x).end()
#define RALL(x) (x).rbegin(),(x).rend()
#define DEBUG(x)  cout << #x << " = " << (x) << endl;
#define SORT(x) sort(ALL(x));
#define RSORT(x) sort(RALL(x));
#define SUM(x) accumulate(ALL(x),0);
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
#define bn(x) ((1<<x)-1)
#define dup(x,y) (((x)+(y)-1)/(y))
using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using pii = pair<int, int>;
using tiii = tuple<int, int, int>;
const ll mod = 1e9+7;
const int INF = (1<<30)-1;
const ll INFLL = (1LL<<62)-1;
const int dx[4] = {1,0,-1,0};
const int dy[4] = {0,1,0,-1};
//cout << fixed << setprecision(10);

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

ll gcd(ll a, ll b) { return b ? gcd(b,a%b) : a;}
ll lcm(ll a, ll b) { return a/gcd(a,b)*b;}

int b[512345];
int a[212345];

int main () {
  int n;
  scanf("%d",&n);
  rep(i,n) scanf("%d",&a[i]);
  int left = 212345, right = left+1;
  rep(i,n) {
    if (i%2 == (n-1)%2) {
      b[left--] = a[i];
    }
    else {
      b[right++] = a[i];
    }
  }

  FOR(i,left+1,right) {
    printf("%d ",b[i]);
  }
  return 0;
}

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

int main() {
  char c;
  cin >> c;
  
  if (c == 'a' || c == 'i' || c == 'u' || c == 'e' || c == 'o') {
    cout << "vowel" << endl;
  }
  else {
    cout << "consonant" << endl;
  }
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define CLR(a)              memset(a, 0, sizeof(a))
#define SET(a, x)           memset(a, x, sizeof(a))
#define SORT(v)             sort(v.begin(), v.end())
#define REV(v)              reverse(v.begin(), v.end())
#define FOR(i, n)           for (int i=0; i<n; i++)
#define FOR1(i, n)          for (int i=1; i<=n; i++)
#define ROF(i, n)           for (int i=n-1; i>=0; i--)
#define ROF1(i, n)          for (int i=n; i>=1; i--)
#define LOOP(i, x, n)       for (int i=x; i<=n; i++)
#define READ(x)             freopen(x, "r", stdin);
#define WRITE(x)            freopen(x, "w", stdout);
#define fastIO()            ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define PI                  acos(-1.0)
#define pb                  push_back
#define mp                  make_pair
#define fi                  first
#define se                  second
#define all(v)              v.begin(), v.end()

using namespace std;

typedef long long              ll;
typedef unsigned long long     ull;
typedef vector<int>            vi;
typedef pair<int, int>         pii;
typedef pair<string, int>      psi;
typedef pair<char, int>        pci;

const double eps = 1e-9;

int fx[] = {-1, 1, 0, 0, -1, -1, 1, 1};
int fy[] = {0, 0, -1, 1, -1, 1, -1, 1};

int kx[] = {1, 1, 2, 2, -1, -1, -2, -2};
int ky[] = {2, -2, 1, -1, 2, -2, 1, -1};

int main()
{
    int a, b; cin >> a >> b;
    for (int i = 1; i <= 1000000; i++){
        if ((int)(i * 0.08) == a && (int)(i * 0.1) == b){
            cout << i << endl;
            return 0;
        }
    }
    cout << "-1" << endl;
    return 0;
}




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

int main()
{
	int N, K, memo, ans = 0;
	int p[1000];
	cin >> N >> K;

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

	for (int i = 0; i < K; i++)
	{
		int abb = 10000;
		for (int u = 0; u < N; u++)
		{
			if (abb > p[u])
			{
				abb = p[u];
				memo = u;
			}
			if (u == N - 1)
			{
				ans += abb;
				p[memo] = 1000;
			}
		}
	}

	cout << ans << endl;

	return 0;
}

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

int main() {
  int N, a, b;
  cin >> N;
  a = N / 10;
  b = N % 1000;
  if ((a % 111 == 0) || (b % 111 == 0)) {
    cout << "Yes" << endl;
  }
  
  else {
    cout << "No" << endl;
  }
}

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

int main()
{
    int n;
    cin >> n;
    vector<int> d(n);
    for(int i=0;i<n;i++){cin >> d[i];}
    sort(d.begin(),d.end());
    cout << d[n/2]-d[n/2 - 1] << endl;
    return 0;
}

Measured memory_bytes: 640
#include <bits/stdc++.h>
using namespace std;
using Int = long long;
typedef pair<int,int> P; typedef map<int,int> MPi; typedef pair<Int,Int> Pl; typedef int8_t shor;
const int mod = 1e9+7; const Int INF=1e18+1LL;
#define END {cout<<ans<<'\n'; return 0;}
#define ALL(v) v.begin(),v.end()
#define Pr(type) priority_queue<type>
#define gPr(type) priority_queue<type,vector<type>,greater<type>>
#define V(type) vector<type>
#define rep(i,n) for(int i=0; i<n; i++)
#define rer(i,st,en,h) for(int i=st; i<=en; i+=h)
#define PU push_back
template<class T> inline bool cmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool cmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }

int n;

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

	cin>>n; int l=pow(2,n); multiset<int>b; Pr(int)a;
	rep(i,l){
		int c; cin>>c; b.insert(c);
	}
	auto i=b.lower_bound(mod); a.push(*(--i)); b.erase(i);
	multiset<int>::iterator it;
	for (int i = 0; i < n; i++){
		Pr(int) u;
		rep(j,(int)pow(2,i)){
			int ma=a.top(); a.pop();
			it=b.lower_bound(ma);
			if(it==b.begin()){cout<<"No"<<'\n'; return 0;}
			u.push(ma); u.push(*(--it)); b.erase(it);
		}
		a=u;
	}
	cout<<"Yes"<<'\n';
}

Measured memory_bytes: 14928
/*input
 
*/
 
 
//assic value of ('0'-'9') is(48 - 57) and (a-z) is (97-122) and (A-Z) is(65-90) and 32 for space
#include<bits/stdc++.h>
using namespace std;
#define ll          long long
#define pb          push_back
#define pii         pair<ll int,ll int>
#define vpii        vector< pii >
#define vi          vector<ll int>
#define vs			vector< string >
#define vvi         vector< vector< ll > >
#define inf			(ll)1e18
#define all(it,a)   for(auto it=(a).begin();it!=(a).end();it++) 
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define rep(i,a,b)	for(ll int i=a;i<b;i++)
#define repr(i,a,b) for(ll int i=a;i>b;i--)
#define lbnd        lower_bound
#define ubnd        upper_bound
#define mp          make_pair
#define whatis(x)   cout << #x << " is " << x << "\n";
#define graph(n)    adj(n,vector< ll > () )
//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
 
const ll N = 1e6+5;
const ll mod=1e9+9; 
int solve()
{
	ll n,k;cin>>n>>k;
	string s;cin>>s;
	ll ans=0;
	// ll ans2=0;
	rep(i,0,n)
	{
		ll j=i;
		ll cnt=0;
		while(j<n && s[j]==s[i]) cnt++,j++;
		ans+=cnt-1;
		i=j-1;
		// ans2++;
	}
	ans+=2*k;
	cout<<min(ans,n-1)<<"\n";
	return 0;
}
 
int main()
{
	auto start = chrono::high_resolution_clock::now();
 
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
 
	ll test_cases=1;
	// cin>>test_cases;
	while(test_cases--)
		solve();
 
	auto stop = chrono::high_resolution_clock::now();
	auto duration = chrono::duration_cast<chrono::milliseconds>(stop-start);
	// cout<<"\nduration: "<<(double)duration.count()<<" milliseconds";
}

Measured memory_bytes: 512
N = int(input())
A = list(map(int, input().split()))
amax = max(A)
max_idx = A.index(amax)
amin = min(A)
min_idx = A.index(amin)

ans_list = []
if amax*amin < 0:
    if abs(amax) >= abs(amin):
        for i in range(N):
            A[i] += amax
            ans_list.append([max_idx+1, i+1])
    else:
        for i in range(N):
            A[i] += amin
            ans_list.append([min_idx+1, i+1])

# print(A)
amax = max(A)
amin = min(A)

if amax > 0:
    for i in range(N-1):
        ans_list.append([i+1, i+2])
elif amin < 0:
    for i in range(N-1, 0, -1):
        ans_list.append([i+1, i])

print(len(ans_list))
for i in range(len(ans_list)):
    print(*ans_list[i])


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

using ll = long long;

constexpr ll base = 211;
constexpr ll M = 1000000000000037LL;

ll dfs(int v, vector<vector<int>>& g, vector<bool>& visited, vector<ll>& hs) {
    visited[v] = true;
    ll res = 1;
    for(auto to : g[v]) {
        if(!visited[to]) {
            (res += dfs(to, g, visited, hs) * base) %= M;
        }
    }
    return hs[v] = res;
}

int main() {
    int N;
    cin >> N;
    vector<vector<int>> g(N);
    for(int i=0; i<N-1; ++i) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    vector<bool> visited(N);
    vector<ll> hs(N);
    dfs(0, g, visited, hs);
    ll res = 0;
    sort(hs.begin(), hs.end());
    for(int i=0; i<N; ++i) {
        auto p = equal_range(hs.begin(), hs.end(), hs[i]);
        res += p.second - p.first - 1;
    }
    res /= 2;
    cout << res << endl;
} 


Measured memory_bytes: 16836
a,b=map(int,input().split())
s=input()
y=0
#c=[0,1,2,3,4,5,6,7,8,9]
for i in range(a):
    if s[i] not in ["0","1","2","3","4","5","6","7","8","9"]:
        y+=1
if s[a]!="-":
    y+=1
for i in range(a+1,a+b+1):
    if s[i] not in ["0","1","2","3","4","5","6","7","8","9"]:
        y+=1
#print(y)
if y==0:
    print("Yes")
else:
    print("No")

Measured memory_bytes: 3064
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<string.h>
#include<iostream>
#include<queue>
#include<stack>
#define Max 1000
#define INF 1000000000000000000
using namespace std;



int main(){

	int a,b;
	scanf("%d%d",&a,&b);
	if(500*a >= b)
		printf("Yes\n");
	else
		printf("No\n");
	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#include<string.h>
 
typedef long long int ll;
#define all(x) (x).begin(), (x).end()
 
using namespace std;

int nxt() {
    int x;
    cin >> x;
    return x;
}

ll nxtl(){
    ll x;
    cin>>x;
    return x;
}
 
void SieveOfEratosthenes(int n,vector <int> &primes) 
{ 
    // Create a boolean array "prime[0..n]" and initialize 
    // all entries it as true. A value in prime[i] will 
    // finally be false if i is Not a prime, else true. 
    bool prime[n+1]; 
    memset(prime, true, sizeof(prime)); 
  
    for (int p=2; p*p<=n; p++) 
    { 
        // If prime[p] is not changed, then it is a prime 
        if (prime[p] == true) 
        { 
            // Update all multiples of p greater than or  
            // equal to the square of it 
            // numbers which are multiple of p and are 
            // less than p^2 are already been marked.  
            for (int i=p*p; i<=n; i += p) 
                prime[i] = false; 
        } 
    } 
  
    // Print all prime numbers 
    for (int p=2; p<=n; p++) 
       if (prime[p]) 
          primes.push_back(p);
} 
 
ll max(ll a,ll b)
{
    if(a>b)
        return a;
    return b;
}
 
ll power(ll x, ll y,ll mod) 
{ 
    ll temp; 
    if( y == 0) 
        return 1; 
    temp = power(x, y/2,mod); 
    if (y%2 == 0) 
        return (temp*temp)%mod; 
    else
        return (((x*temp)%mod)*temp)%mod; 
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n=nxt();
    vector <int> v(n+1);
    vector <pair<ll,ll> > left,right;
    left.resize(n+1,{0,0});
    right.resize(n+1,{n+1,n+1});
    for(int i=1;i<=n;i++)
        cin>>v[i];

    stack <int> s1,s2,temp;
    for(int i=n;i>=1;i--)
    {
        while(s1.size()&&v[s1.top()]<v[i])
        {
            left[s1.top()].first=i;
            int x=s1.top();
            s1.pop();
            temp.push(x);
        }
        while(s2.size()&&v[s2.top()]<v[i])
        {
            left[s2.top()].second=i;
            s2.pop();
        }
        s1.push(i);
        while(temp.size())
        {
            int x=temp.top();
            temp.pop();
            s2.push(x);
        }

    }

    while(s1.size())
        s1.pop();
    while(s2.size())
        s2.pop();
    while(temp.size())
        temp.pop();
    for(int i=1;i<=n;i++)
    {
        while(s1.size()&&v[s1.top()]<v[i])
        {
            right[s1.top()].first=i;
            int x=s1.top();
            s1.pop();
            temp.push(x);
        }
        while(s2.size()&&v[s2.top()]<v[i])
        {
            right[s2.top()].second=i;
            s2.pop();
        }
        s1.push(i);
        while(temp.size())
        {
            int x=temp.top();
            temp.pop();
            s2.push(x);
        }

    }

    ll test=0;
    for(int i=1;i<=n;i++)
    {
        ll count=0;
        if(left[i].first!=0)
        {
            count+=((left[i].first-left[i].second)*(right[i].first-i));
        }
        if(right[i].first!=0)
        {
            count+=((i-left[i].first)*(right[i].second-right[i].first));
        }
        test+=(count*v[i]);
    }    

    cout<<test<<endl;
    
    return 0;   
}


 
 


Measured memory_bytes: 4096
#include <bits/stdc++.h>
using namespace std;
int main (){
    long long N,ans=0;
    cin >> N;
    vector<long long> v(3*N,0);
    for(int i=0;i<3*N;i++){
        cin >> v.at(i);
    }
    sort(v.begin(),v.end(),greater<long long>());

    for(int i=1;i<2*N;i+=2){
        ans += v.at(i);
    }
    cout << ans << endl;

}

Measured memory_bytes: 2560
a = list(map(int, input().split()))
n = a[0]
k = a[1]
Sum = 0
 
for i in range(n-k+2):
  Sum += int((2*n-k-i+1)*(k+i)/2-(k+i-1)*(k+i)/2+1)
print(Sum%(10**9+7))

Measured memory_bytes: 9152
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i=0; i<(int)(n); i++)
#define all(x) x.begin(), x.end()
#define mod 1000000007
typedef long long ll;

int main(){
  int n, k;
  cin >> n >> k;
  vector<int> flags(10, 0);
  rep(i, k){
    int num;
    cin >> num;
    flags[num] = 1;
  }
  while(true){
    string str = to_string(n);
    bool isok = true;
    rep(i, str.length()){
      if(flags[str[i]-'0'] == 1) isok = false;
    }
    if(isok){
      cout << n << endl;
      return 0;
    }
    n++;
  }
}
  
  

Measured memory_bytes: 256
import java.util.Scanner;

public class Main{

	public static void main(String args[]){

		Scanner sc = new Scanner(System.in);

		int n=sc.nextInt();
		int m=sc.nextInt();
		int X=sc.nextInt();
		int Y=sc.nextInt();
		int x,xmax=-100;
		int y,ymax=100;

		boolean safety = false;

		for (int i=0;i<n;++i){
			x=sc.nextInt();
			if(xmax<x)xmax=x;
		}
		for (int i=0;i<m;++i){
			y=sc.nextInt();
			if(ymax>y)ymax=y;
		}

		if (ymax>xmax){
			for(int z=xmax+1;z<=ymax&& safety==false;++z){
				if(X<z && z<=Y) safety=true;
			}
		}

		if (safety== true)System.out.println("No War");
		else System.out.println("War");

	}
}

Measured memory_bytes: 22608
#include <stdio.h>

int main(){
  int p,q,r;
  if(scanf("%d",&p)==1 && scanf("%d",&q)==1 && scanf("%d",&r)==1){}
  
  int pq,qr,rp;
  pq = p + q;
  qr = q + r;
  rp = r + p;
  
  if(pq <= qr && pq <= rp){
    printf("%d",pq);
  }else if(qr <= rp){
    printf("%d",qr);
  }else{
    printf("%d",rp);
  }
  
  return 0;
}

Measured memory_bytes: 128
#include <stdio.h>
int main(void)
{
	int a, b;
	char op;

	while(scanf("%d %c %d", &a, &op, &b)!=EOF && op!='?'){
		switch(op){
			case '+': printf("%d\n", a+b);
			          break;
			case '-': printf("%d\n", a-b);
			          break;
			case '*': printf("%d\n", a*b);
			          break;
			case '/': printf("%d\n", a/b);
			          break;
		}
	}
	return 0;
}

Measured memory_bytes: 600
#include <bits/stdc++.h>
#include <math.h>
#define ALL(a)    a.begin(), a.end() 
#define rep(i, K, N)  for(long long int i = K; i < N; i++)
#define ll long long int
using namespace std;

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

if(N == 1 && M == 1){cout << 1;exit(0);}
if(N == 2 || M == 2){cout << 0;exit(0);}
if(N == 1 && M != 1){cout << M - 2;exit(0);}
if(N != 1 && M == 1){cout << N - 2;exit(0);}
cout << (N - 2)*(M - 2);
}

Measured memory_bytes: 3624
#pragma GCC optimize("Ofast")
#include<bits/stdc++.h>
//#include<boost/multiprecision/cpp_int.hpp>
//#include<boost/multiprecision/cpp_dec_float.hpp>
//namespace mp=boost::multiprecision;
//#define mulint mp::cpp_int
//#define mulfloat mp::cpp_dec_float_100
using namespace std;
struct __INIT{__INIT(){cin.tie(0);ios::sync_with_stdio(false);cout<<fixed<<setprecision(15);}} __init;
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
constexpr int MOD=1000000007;
//constexpr int MOD=998244353;
#define INF (1<<30)
#define LINF (lint)(1LL<<56)
#define endl "\n"
#define rep(i,n) for(lint (i)=0;(i)<(n);(i)++)
#define reprev(i,n) for(lint (i)=(n-1);(i)>=0;(i)--)
#define Flag(x) (1<<(x))
#define Flagcount(x) __builtin_popcountll(x)
#define pint pair<int,int>
#define pdouble pair<double,double>
#define plint pair<lint,lint>
#define fi first
#define se second
typedef long long lint;
int dx[8]={1,1,0,-1,-1,-1,0,1};
int dy[8]={0,1,1,1,0,-1,-1,-1};
const int MAX_N=2e5+5;
//struct edge{lint to,num;};

int A[200000];
vector<int> edge[200000];
int ans[200000];
bool reach[200000];
int dp[200000];
stack<pint> save;

void dfs(int now){
    if(reach[now]) return;
    reach[now]=true;
    int put=lower_bound(dp,dp+200000,A[now])-dp;
    save.push(pint(put,dp[put]));
    dp[put]=A[now];
    ans[now]=lower_bound(dp,dp+200000,INF)-dp;
    rep(i,edge[now].size()) dfs(edge[now][i]);
    pint rev=save.top();
    save.pop();
    dp[rev.fi]=rev.se;
}

int main(void){
    int N;
    cin >> N;
    rep(i,N) cin >> A[i];
    rep(i,200000) dp[i]=INF;
    rep(i,N-1){
        int u,v;
        cin >> u >> v;
        u--,v--;
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    dfs(0);
    rep(i,N) cout << ans[i] << endl;
}

Measured memory_bytes: 35420