akhauriyash/Code-Regression huggingface dataset:
#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {
  string S;
  cin >> S;
  vector<int> mods(2019,0);
  mods[0]=1;
  int current = 0;
  int keta = 1;
  for(int i=(int)S.size()-1;i>=0;i--) {
    current=(stoi(S.substr(i,1))*keta+current)%2019;
    mods[current]++;
    keta = keta*10%2019;
  }
  int result = 0;
  for(int j : mods) {
    if(j>=2) {
      result+=j*(j-1)/2;
    }
  }

  cout << result << endl;
}


Measured memory_bytes: 3732
#include "bits/stdc++.h"
using namespace std;
#define MOD 1000000007
#define inf 0x3f3f3f3f3f3f3f3f
#define pi acos(-1.0)
#define ri register int
#define int long long
#define all(x) x.begin(), x.end()
#ifdef ONLINE_JUDGE
const int maxn = 2e2 + 10;
#else
const int maxn = 1e3 + 10;
#endif
//__builtin_popcount
int arr[maxn], N, M;
signed main() {
#ifdef ONLINE_JUDGE
    ios::sync_with_stdio(false);
    cin.tie(0);
#endif
    // freopen("C:\Users\hjw\Downloads\testdata (4).in", "r", stdin);
    cin >> N >> M;
    int ans = 0;
    for (ri i = 1; i <= N; ++i) {
        arr[i] = 2;
    }
    for (ri i = 1; i <= M; ++i) {
        arr[i + N] = 1;
    }
    for (int i = 1; i <= N + M; ++i) {
        for (ri j = i + 1; j <= N + M; ++j) {
            if ((arr[i] + arr[j]) % 2 == 0)
                ++ans;
        }
    }
    cout << ans << endl;
#ifndef ONLINE_JUDGE
    system("pause");
#endif
    return 0;
}

Measured memory_bytes: 504
mod io{
    use std::io::*;
    pub fn read<T: ::std::str::FromStr>()->T{
        let stdin=stdin();
        let ret=stdin.lock().bytes().map(|c|c.unwrap()as char)
        .skip_while(|c|c.is_whitespace())
        .take_while(|c|!c.is_whitespace())
        .collect::<String>().parse().ok().unwrap();
        ret
    }
}
use io::read;
fn main(){
    let a=read::<i32>();
    let b=read::<i32>();
    let c=read::<i32>();
    let d=read::<i32>();
    println!("{}",if a+b>c+d{"Left"}
    else if a+b<c+d{"Right"}
    else{"Balanced"})
}

Measured memory_bytes: 4352
#include<bits/stdc++.h>
using namespace std;
int n;
int hao=0;
int a[15];
void DFS(int now){
//    printf("now:%d\n",now);
    if(now==n+1){
        for(int i=1;i<=n;i++){
            printf("%c",a[i]+'a'-1);
        }
        printf("\n");
        return ;
    }
    for(int i=1;i<=hao;i++){
        a[now]=i;
        DFS(now+1);
    }
    a[now]=hao+1;
    hao++;
    DFS(now+1);
    hao--;
    return ;
}
int main(){
    scanf("%d",&n);
    DFS(1);
    return 0;
}


Measured memory_bytes: 1536
// 基本テンプレート

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <functional>
using namespace std;

#define rep(i,a,n) for(int (i)=(a); (i)<(n); (i)++)
#define repq(i,a,n) for(int (i)=(a); (i)<=(n); (i)++)
#define repr(i,a,n) for(int (i)=(a); (i)>=(n); (i)--)
#define int long long int

template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}

typedef pair<int, int> pii;
typedef long long ll;

int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
constexpr ll INF = 1001001001001001LL;
constexpr ll MOD = 1000000007LL;

signed main() {
    int K; cin >> K;
    int rec[60], ans[60];
    int div = K / 50, md = K % 50;
    rep(i,0,50) rec[i] = div + (i < md);

    rep(i,0,50) {
        int S = 0;
        rep(j,0,50) {
            if(i != j) S += rec[j];
        }
        ans[i] = 50 * (rec[i] + 1) - S - 1;
    }
    cout << 50 << endl;
    rep(i,0,50) cout << (i ? " " : "") << ans[i];
    cout << endl;
    return 0;
}


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

#define _USE_MATH_DEFINES

#include <math.h>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int N, M;
    cin >> N >> M;

    int needed = 0;
    while (M--) {
        int Ai;
        cin >> Ai;
        needed += Ai;
    }

    cout << (max(-1, N - needed)) << endl;

    return 0;
}


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

int main()
{
  int n;
  int k;
  cin >> n >> k;
  vector<int> d(10, 0);
  for (int i = 0; i < k; i++)
  {
    int buf;
    cin >> buf;
    d.at(buf) = 1;
  }

  for (int i = n; i < 100000; i++)
  {
    int flag = 1;
    int buf = i;
    while (buf != 0)
    {
      if (d.at(buf % 10) == 1)
      {
        flag = 0;
        break;
      }
      buf /= 10;
    }
    if (flag == 1)
    {
      cout << i << endl;
      break;
    }
  }
}


Measured memory_bytes: 3624
use std::io::Read;

pub fn read_stdin() -> String {
    let mut s = String::new();
    ::std::io::stdin().read_to_string(&mut s).unwrap();
    s
}

pub trait Parse {
    fn to<T>(&mut self) -> T
    where
        T: std::str::FromStr;
}

impl<'a> Parse for std::str::SplitWhitespace<'a> {
    fn to<T>(&mut self) -> T
    where
        T: std::str::FromStr,
    {
        let word = self.next().unwrap();
        word.parse().ok().unwrap()
    }
}

fn factorization(x: u64) -> Vec<u64> {
    let mut base = x;
    let mut div = 2;
    let mut v = Vec::new();
    if x != 1 {
        v.push(1)
    };

    let last = (base as f64).sqrt() as u64;
    while last >= div {
        if base % div == 0 {
            base /= div;
            v.push(div);
            continue;
        }
        div += 1;
    }
    v.push(base);
    v
}


fn main() {
    let source = read_stdin();
    let mut iter = source.split_whitespace();
    let a = iter.to();
    let b = iter.to();
    let mut aa = factorization(a);
    aa.dedup();
    let mut bb = factorization(b);
    bb.dedup();
    aa.extend(&bb);
    aa.sort();

    if aa.len() <= 1 {
        println!("{}", aa.len());
        return;
    }

    let mut ans = Vec::new();
    for w in aa.windows(2) {
        if w[0] == w[1] {
            ans.push(w[0]);
        }
    }
    ans.dedup();

    println!("{}", ans.len());
}

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


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

    int C[N], V[N];
    vector<int> lis(N);
    for(int i = 0; i < N; ++i){
        cin >> V[i];
        
    }
    for(int i = 0; i < N; ++i){
        cin >> C[i];
        lis[i] = V[i] - C[i];
    }

    int ans = 0;
    sort(lis.begin(), lis.end());
    for(int i = N - 1; i >= 0 && lis[i] >= 0; --i){
        ans += lis[i];
    }

    cout << ans << endl;
}


Measured memory_bytes: 256
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, sub

sys.setrecursionlimit(10000)

mod = 10**9 + 7


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


def mul(a, b):
    return ((a % mod) * (b % mod)) % mod


def power(x, y):
    if y == 0:
        return 1
    elif y == 1:
        return x % mod
    elif y % 2 == 0:
        return power(x, y//2)**2 % mod
    else:
        return power(x, y//2)**2 * x % mod


def div(a, b):
    return mul(a, power(b, mod-2))


@mt
def slv(N, A):

    def perm(n):
        p = 1
        for i in range(1, n+1):
            p *= i
            p %= mod
        return p

    pn = perm(N)
    sp = [0]
    for i in range(1, N+1):
        sp.append((sp[-1] + div(pn, i)) % mod)

    ans = (sp[-1] * A[0]) % mod
    for i in range(1, N):
        ans += ((sp[i+1] - sp[1]) * A[i]) % mod
        ans %= mod
        ans += ((sp[N-i] - sp[0]) * A[i]) % mod
        ans %= mod
    return ans


def main():
    N = read_int()
    A = read_int_n()
    print(slv(N, A))


if __name__ == '__main__':
    main()


Measured memory_bytes: 16636
import scala.io.StdIn.readLine

object Main extends App {
  val input = readLine().split(" ").map(_.toInt)
  val num = input(0)
  val demand = input(1)

  for (i <- 0 to 100) {
    val calc = 1 + (num - 1) * i
    if (calc >= demand) {
      println(i);
      sys.exit
    }
  }

}

Measured memory_bytes: 25544
#include<bits/stdc++.h>
#define all(vec) vec.begin(),vec.end()
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
const ll MOD=10000000;
const ll INF=1000000001;
const ll LINF=4000000000000000010;
const double EPS=1e-9;
int dx[5]={0,1,0,-1,0};
int dy[5]={1,0,-1,0,0};
int main(){
    int x;cin>>x;
    int d[31];
    d[9]=5;
    for(int i=8;i>=1;i--){
        d[i]=(d[i+1]-1+7)%7;
    }
    for(int i=10;i<=30;i++){
        d[i]=(d[i-1]+1)%7;
    }
    if(d[x]==0){
        cout<<"mon"<<endl;
    }else if(d[x]==1){
        cout<<"tue"<<endl;
    }else if(d[x]==2){
        cout<<"wed"<<endl;
    }else if(d[x]==3){
        cout<<"thu"<<endl;
    }else if(d[x]==4){
        cout<<"fri"<<endl;
    }else if(d[x]==5){
        cout<<"sat"<<endl;
    }else{
        cout<<"sun"<<endl;
    }
}


Measured memory_bytes: 3112
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
#define rep(i,n) for(int i = 0; i < ((int)(n)); i++)   // 0-indexed昇順

int main() {
    int N; cin >> N;
    vector<int> A(N), B(N), C(N-1);
    rep(i,N) cin >> A.at(i);
    rep(i,N) cin >> B.at(i);
    rep(i,N-1) cin >> C.at(i);
    ll sum = 0;
    int prev = 0;
    rep(i,N) {
        sum += B[i];
        if (i > 0 && A[i] == prev + 1) sum += C[prev-1];
        prev = A[i];
    }
    cout << sum << endl;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#define rep(i,n) for(int i=0; i<(n); ++i)
#define rep2(i,n) for(int i=1; i<=(n); ++i)
#define all(x) (x).begin(),(x).end()
#define Sort(x) sort((x).begin(),(x).end())
#define Sort2(x) sort((x).begin(),(x).end(), greater<int>())
#define pb push_back
using namespace std;
using ll = long long;
using P = pair<int,int>;
using Graph = vector<vector<int>>;

int main()
{
    int n,k; cin >> n >> k;
    vector<int> a(n); rep(i, n) cin >> a[i];
    for(int i=k; i<n; i++){
        if (a[i] > a[i-k]) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}

/*
g++ c.cpp
./a.out

oj d https://atcoder.jp/contests/abc172/tasks/abc172_c
g++ c.cpp
oj t
*/


Measured memory_bytes: 3984
#include <bits/stdc++.h>
using namespace std;
int sed(int i){
  int sum = 0;
  while(i > 0){
    sum += i % 10;
    i /= 10;
  }
  return sum;
}
int main(){
  int n;
  cin >> n;
  if(n == 10 || n == 100 || n == 1000 || n == 10000 || n == 100000) {cout << 10 << endl; return 0;}
  else cout << sed(n) << endl;
}
  


Measured memory_bytes: 256
#include <bits/stdc++.h> 
  
#define for1(i,a,b) for (int i = a; i <= b; i++)
#define for2(i,a,b) for (int i = a; i >= b; i--)
#define int long long

using namespace std;

signed main() {
    string s;
    cin >> s;
    if (s[s.size()-1]=='s') cout << s+"es";
    else cout << s+"s";
}

Measured memory_bytes: 3628
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

int main()
{
    int n,d;
    cin >>n >>d;
    int a = 0;
    rep(i,n)
    {
        int p;
        cin >>p;
        if(p-d>0) a+=p-d;
    }

    if(!a) cout << "kusoge" << endl;
    else cout << a << endl;
    return 0;
}

Measured memory_bytes: 3084
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 1010;
const int INFTY = 1000000000;
struct Node{
    int to;
    int value;
    void set(int a,int b){
        to  = a;
        value = b;
    }
    void real(){
        value*=-1;
    }
};
bool operator<(const Node&a,const Node &b){
    return a.value<b.value;
}
vector<Node> g[maxn];
priority_queue<Node> q;
int d[maxn];
bool vis[maxn];
int p[maxn];
int n;
void prim(){
    for(int i = 0;i<n;++i){
        d[i] = INFTY;
        vis[i] = false;
        p[i] = -1;
    }
    d[0] = 0;
    Node work;
    work.set(0,0);
    q.push(work);
    while(!q.empty()){
        work = q.top();
        work.real();
        q.pop();
        int from = work.to;
        int len = g[from].size();
        if(vis[from])continue;
        vis[from] = true;
        while(len--){
            int to = g[from][len].to;
            int add = g[from][len].value;
            if(!vis[to]&&(add<d[to])){
                d[to] = add;
                p[to] = from;
                work.set(to,d[to]);
                work.real();
                q.push(work);
            }
        }
    }
}
int main(){
    int tmp,ans;
    Node work;
    scanf("%d",&n);
    for(int i = 0;i<n;++i){
        for(int j  = 0;j<n;++j){
            scanf("%d",&tmp);
            if(tmp!=-1){
                work.set(j,tmp);
                g[i].push_back(work);
            }
        }
    }
    prim();
    ans = 0;
    for(int i = 0;i<n;++i){
        ans+=d[i];
    }
    printf("%d\n",ans);
    return 0;
}



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

using namespace std;

int main(int argc, char const *argv[]) {
	const int MOD = 1000000007;
	int n, m;
	scanf("%d%d", &n, &m);
	int x[100000];
	int y[100000];
	for(int i = 0; i < n; i++) {
		scanf("%d", &x[i]);
	}
	for(int i = 0; i < m; i++) {
		scanf("%d", &y[i]);
	}
	long long int xt = 0;
	int xl = 0;
	for(int i = 0; i < n - 1; i++) {
		xl = (xl + (((long long int)(x[i + 1] - x[i])) * (i + 1)) % MOD) % MOD;
		xt = (xt + xl) % MOD;
	}
	long long int yt = 0;
	int yl = 0;
	for(int i = 0; i < m - 1; i++) {
		yl = (yl + (((long long int)(y[i + 1] - y[i])) * (i + 1)) % MOD) % MOD;
		yt = (yt + yl) % MOD;
	}
	printf("%lld\n", (xt * yt) % MOD);
	return 0;
}


Measured memory_bytes: 1024
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <cstdio>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdlib>
#include <cstdio>
using namespace std;

#define next '\n'
#define rep(i, n) for(int (i) = (0); (i) < (n); (i++))
using ll = long long;

int a[5];

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

    string ans = "Yay!";

    int k;
    rep(i, 5){
        cin >> a[i];
    }
    cin >> k;

    for(int i = 0; i < 5; ++i){
        for(int j = i; j < 5; ++j){
            if(abs(a[i] - a[j]) > k){
                ans = ":(";
            }
        }
    }

    cout << ans << next;
}

Measured memory_bytes: 256
package main

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

type bufReader struct {
	r   *bufio.Reader
	buf []byte
	i   int
}

var reader = &bufReader{
	bufio.NewReader(os.Stdin),
	make([]byte, 0),
	0,
}

func (r *bufReader) readLine() {
	if r.i < len(r.buf) {
		return
	}
	r.buf = make([]byte, 0)
	r.i = 0
	for {
		line, isPrefix, err := r.r.ReadLine()
		if err != nil {
			panic(err)
		}
		r.buf = append(r.buf, line...)
		if !isPrefix {
			break
		}
	}
}

func (r *bufReader) next() string {
	r.readLine()
	from := r.i
	for ; r.i < len(r.buf); r.i++ {
		if r.buf[r.i] == ' ' {
			break
		}
	}
	s := string(r.buf[from:r.i])
	r.i++
	return s
}

func (r *bufReader) nextLine() string {
	r.readLine()
	s := string(r.buf[r.i:])
	r.i = len(r.buf)
	return s
}

var writer = bufio.NewWriter(os.Stdout)

func next() string {
	return reader.next()
}

func nextInt64() int64 {
	i, err := strconv.ParseInt(reader.next(), 10, 64)
	if err != nil {
		panic(err)
	}
	return i
}

func nextInt() int {
	return int(nextInt64())
}

func nextLine() string {
	return reader.nextLine()
}

func out(a ...interface{}) {
	fmt.Fprintln(writer, a...)
}

func max64(x, y int64) int64 {
	if x > y {
		return x
	}
	return y
}

func max(x, y int) int {
	return int(max64(int64(x), int64(y)))
}

func min64(x, y int64) int64 {
	if x < y {
		return x
	}
	return y
}

func min(x, y int) int {
	return int(min64(int64(x), int64(y)))
}

func abs64(x int64) int64 {
	if x < 0 {
		return -x
	}
	return x
}

func abs(x int) int {
	return int(abs64(int64(x)))
}

func joinInt64s(a []int64, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.FormatInt(v, 10)
	}
	return strings.Join(b, sep)
}

func joinInts(a []int, sep string) string {
	b := make([]string, len(a))
	for i, v := range a {
		b[i] = strconv.Itoa(v)
	}
	return strings.Join(b, sep)
}

func divUp64(x, y int64) int64 {
	return (x + y - 1) / y
}

func divUp(x, y int) int {
	return int(divUp64(int64(x), int64(y)))
}

func gcd64(x, y int64) int64 {
	if x < y {
		x, y = y, x
	}
	for y != 0 {
		x, y = y, x%y
	}
	return x
}

func gcd(x, y int) int {
	return int(gcd64(int64(x), int64(y)))
}

func lcm64(x, y int64) int64 {
	return x * y / gcd64(x, y)
}

func lcm(x, y int) int {
	return int(lcm64(int64(x), int64(y)))
}

func pow64(x, y int64) int64 {
	return int64(math.Pow(float64(x), float64(y)))
}

func pow(x, y int) int {
	return int(pow64(int64(x), int64(y)))
}

func main() {
	solve()
	writer.Flush()
}

type pair struct {
	i, j int
}

var a = []string{"dreamer", "dream", "eraser", "erase"}

func solve() {
	N, x := nextInt(), nextInt()
	a := make([]int, N)
	for i := 0; i < N; i++ {
		a[i] = nextInt()
	}
	ans := 0
	if a[0] > x {
		ans = a[0] - x
		a[0] = x
	}
	for i := 0; i < N-1; i++ {
		if d := a[i] + a[i+1] - x; d > 0 {
			if a[i+1] >= d {
				a[i+1] -= d
			} else {
				a[i] -= d - a[i+1]
				a[i+1] = 0
			}
			ans += d
		}
	}
	out(ans)
}


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

int main() {
  int N;
  cin >> N;
  int ans = (N/1000 + 1)*1000 - N;
  if (ans != 1000) cout << (N/1000 + 1)*1000 - N << endl;
  else cout << 0 << endl;
}

Measured memory_bytes: 3632
#!/usr/bin/env python3
from collections import deque
import sys
input = sys.stdin.readline

n, m = map(int, input().split())
edges = [[] for _ in range(n)]
for _ in range(m):
    a, b = map(int, input().split())
    edges[a - 1].append(b - 1)
    edges[b - 1].append(a - 1)

que = deque()
dist = [float('inf')] * n
prev = [-1] * n
dist[0] = 0
que.append(0)
while que:
    now = que.popleft()
    for edge in edges[now]:
        if dist[edge] > dist[now] + 1:
            dist[edge] = dist[now] + 1
            prev[edge] = now + 1
            que.append(edge)


print('Yes')
for i in range(1, n):
    print(prev[i])



Measured memory_bytes: 37796
k=50
l=[["." if h<k else "#" for w in range(2*k)] for h in range(2*k)]
a,b=map(int,input().split())

#a->white. b->black#
aa=0
for y in range(k+1,k*2,2):
  if aa==a-1:break

  for x in range(0,2*k,2):
    if aa==a-1:break
    l[y][x]="."
    aa+=1

bb=0
for y in range(0,k-1,2):
  if bb==b-1:break
  for x in range(0,2*k,2):
    if bb==b-1:break
    l[y][x]="#"
    bb+=1

print(2*k,2*k)
for i in l:
  print("".join(i))

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

typedef long long ll;

struct node{
	int t, nxt, flag;
}edge[200050];

int head[100050], cnt, typ[100050];

void add(int u, int v, int flag){
	edge[++cnt] = (node){v, head[u], flag};
	head[u] = cnt;
}

ll getans(int x){
	queue<int> q;
	typ[x] = 0;
	int cnt[3], edget = 0, dcnt = 1, flag1 = 0;
	cnt[0] = 1;
	cnt[1] = cnt[2] = 0;
	q.push(x);
	while(!q.empty()){
		int u = q.front(); q.pop();
		for(int i = head[u]; i; i = edge[i].nxt){
			int v = edge[i].t, ncol;
			if(edge[i].flag) edget++;
			if(typ[v]==-1) dcnt++;
			if(edge[i].flag == 1) ncol = (typ[u]+1) % 3;
			else ncol = (typ[u]+2)%3;
			if(typ[v]==-1){
				typ[v] = ncol;
				cnt[ncol]++;
				q.push(v);
			}
			else if(typ[v] != ncol) flag1 = 1; 
		}
	}
	if(flag1) return 1ll*dcnt * dcnt;
	else if(!cnt[0] || !cnt[1] || !cnt[2]) return edget;
	else {
		return 1ll*cnt[0] * cnt[1] + 1ll*cnt[1] * cnt[2] + 1ll*cnt[2] * cnt[0];
	}
}

int main(){
	ll ans = 0;
	int n, m;
	memset(typ, -1, sizeof(typ));
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= m; i++){
		int u, v;
		scanf("%d %d", &u, &v);
		add(u, v, 1);
		add(v, u, 0);
	}
	for(int i = 1; i <= n; i++) if(typ[i] == -1){
		ans += getans(i);
	}
	printf("%lld", ans);
}

Measured memory_bytes: 3712
using System;
using System.Collections.Generic;
using System.Linq;

namespace test
{
    class MainClass
    {
        public static void Main(string[] args)
        {

            //問題162


            int x = int.Parse(Console.ReadLine());

            //Console.WriteLine(x);

            if (x >= 30)
            {
                Console.WriteLine("Yes");
            }
            else
            {
                Console.WriteLine("No");
            }
        }

    }





    
}


Measured memory_bytes: 27480
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <utility>
#include <functional>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;
inline int toInt(string s) { int v; istringstream sin(s); sin >> v; return v;}
template<class T> inline string toStr(T x) { ostringstream sout; sout << x; return sout.str();}
typedef vector<int> vi;
typedef vector<vi>  vvi;
typedef vector<string> vs;
typedef pair<int, int> pii;
typedef long long ll;
#define ALL(a) (a).begin(),(a).end()
#define RALL(a) (a).rbegin(),(a).rend()
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define REP(i,n) FOR(i,0,(n)-1)
const double EPS = 1e-12;
const double PI = acos(-1.0);
const int INF = INT_MAX/10;

int josephus(int n, int k, int s) {
	int ret = k * s;
	while(ret > n) {
		ret = ((ret - n) * k - 1) / (k - 1);
	}
	return ret;
}

int main() {
	int n, m;
	while(cin >> n, n) {
		cin >> m;

		cout << josephus(n, m, n) << endl;
	}

	return 0;
}

Measured memory_bytes: 1156
#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define REPR(i, n) for (int i = n - 1; i >= 0; i--)
#define INF 1LL << 60;
#define LLINF 1e12
#define PI 3.14159265359
#define ALL(a) (a).begin(), (a).end()
int dy[] = {1, 0, -1, 0};
int dx[] = {0, 1, 0, -1};
int ny, nx;
typedef long long ll;
using namespace std;

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

ll lcm(ll m, ll n)
{
    if ((0 == m) || (0 == n))
        return 0;
    return ((m / gcd(m, n)) * n);
}

ll llpow(ll x, ll y)
{
    ll ans = 1;
    REP(i, y)
    ans *= x;
    return ans;
}

ll llmin(ll x, ll y) { return x < y ? x : y; }
ll llmax(ll x, ll y) { return x > y ? x : y; }

unsigned GetDigit(unsigned num) { return to_string(num).length(); }

template <typename Container>
bool exist_in(const Container &c, const typename Container::value_type &v)
{
    return (c.end() != std::find(c.begin(), c.end(), v));
}

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 nCr(int n, int r)
{
    if (n == r or n == 0)
        return 1;
    if (n < r)
        return 0;
    if (r == 1)
        return n;
    return nCr(n - 1, r - 1) + nCr(n - 1, r);
}

//std::cout << std::defaultfloat << std::setprecision(10);
////////////////////////////////////////
int main()
{
    ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);

    string S; cin >> S;
    string T; cin >> T;

    REP(i,S.size()){
        if(S[i]!=T[i]){
            cout << "No" << endl;
            return 0;
        }
    }

    cout << "Yes" << endl;

    return 0;
}


Measured memory_bytes: 3656
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		try(Scanner sc = new Scanner(System.in)) {
			
			int n = sc.nextInt();
			int k = sc.nextInt();
			
			
			PriorityQueue<Long> queue = new PriorityQueue<>(10, Collections.reverseOrder());
			//List<Long> hList = new ArrayList<Long>();
			for(int i = 0 ; i < n ; i++ )  {
				queue.add(sc.nextLong());
			}
			
//			
			for(int i = 0 ; i < k ; i++ ) {
				queue.poll();
			}
			
			System.out.println(queue.stream().mapToLong(l -> l).sum());
		}
	}
}

Measured memory_bytes: 95576
s = str(input())
n = len(s)
x = [0]*2019
x[0] = 1
m = 0
j = 1
for i in range(n):
  m = (m + int(s[-i-1])*j)%2019
  x[m] += 1
  j = (j*10)%2019
ans = 0
for i in range(2019):
  ans += (x[i]*(x[i]-1))//2
print(ans)
  
  


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

int main(){
    int N; cin >> N;
    vector <int> A(N+1);
    vector <int> B(N);
    rep(i,N+1) cin >> A[i];
    rep(i,N) cin >> B[i];
    
    long long ans=0;
    //N人の勇者チャレンジ
    rep(i,N){
        int sen=B[i]-A[i];
        if (B[i]>=A[i] && (sen < A[i+1])){//隣町の全ボスまでを倒す戦闘力がないとき
            ans=ans+A[i]+sen;
            A[i+1]-=sen;//隣町のボスにダメージを与えとく
        }
        else if (B[i]>=A[i] && (sen >= A[i+1])){//隣町の全ボスも倒すことができるとき
            ans=ans+A[i]+A[i+1];
            A[i+1]=0;
        }else if (B[i]<A[i]){//最初の町の全ボスすらも倒せないとき
            ans+=B[i];
        }
    }
    cout << ans << endl;
}

Measured memory_bytes: 1024
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace AtCoder
{
    class Program
    {
        private static string Read() { return Console.ReadLine(); }
        private static int ReadInt() { return int.Parse(Read()); }
        private static long ReadLong() { return long.Parse(Read()); }
        private static double ReadDouble() { return double.Parse(Read()); }
        private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
        private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
        private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }

        static IEnumerable<bool> Solve(int N, int K, int Q, int[] A)
        {
            var sums = new int[N];
            for (int i = 0; i < Q; ++i) { ++sums[A[i]]; }
            return sums.Select(sum => K - Q + sum > 0);
        }

        static void Main(string[] args)
        {
            var V = ReadInts();
            int N = V[0], K = V[1], Q = V[2];
            var A = new int[Q];
            for (int i = 0; i < Q; ++i) { A[i] = ReadInt() - 1; }
            foreach (bool ans in Solve(N, K, Q, A))
            {
                Console.WriteLine(ans ? "Yes" : "No");
            }
        }
    }
}


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

int main(){
  long long n;
  cin >> n;
  long long a=1;
  for(long long i=0; i<n; i++){
    long long x;
    cin >> x;
    a=lcm(a,x);
  }
  cout << a << endl;
}

Measured memory_bytes: 3644
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <bitset>
#include <cstring>
using namespace std;
#define FOR(I,A,B) for(int I = (A); I < (B); ++I)
#define CLR(mat) memset(mat, 0, sizeof(mat))
typedef long long ll;

int main()
{
  int sum = 0;
FOR(i,0,5) {
int in; cin >> in;
sum += max(in,40);
}
cout << sum/5<<endl;
return 0;
}

Measured memory_bytes: 3016
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>

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

using namespace std;
//隣接数の数え上げ

int main(){
    ll N,res;

    cin >> N;

    vector <ll> a(N);

    REP(i,N)
    {
        cin >> a[i];
    }

    vector <ll> ppp(100001);


    for(auto t:a)
    {
        if(t == 0)
        {
            ppp[t]++;
            ppp[t+1]++;
        }
        else
        {
            ppp[t-1]++;
            ppp[t]++;
            ppp[t+1]++;
        }
    }
    res = *max_element(ppp.begin(),ppp.end());

    cout << res << endl;

    return 0;
}

Measured memory_bytes: 1024
module Main where
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Data.Graph
import Control.Monad
import Data.List(sortOn, foldl')
import Data.Maybe
import qualified Data.Array.IO as MV
import qualified Data.Array as A

readIntPair :: B.ByteString -> (Int,Int)
readIntPair s = p
    where
    Just p = do
        (n1, s') <- B.readInt s
        (n2, _ ) <- B.readInt (B.tail s')
        return (n1,n2)
readIntTriple :: B.ByteString -> (Int,Int, Int)
readIntTriple s = p
    where
    Just p = do
        (n1, s') <- B.readInt s
        (n2, s'') <- B.readInt (B.tail s')
        (n3, _) <- B.readInt (B.tail s'')
        return (n1,n2,n3)

main :: IO ()
main = do
    (n,m) <- fmap readIntPair B.getLine 
    xs <- fmap (map (fst . fromJust . B.readInt) . B.words) B.getLine
    es <- fmap (map readIntTriple . B.lines) B.getContents
    parent <- MV.newArray (1,n) 0 :: IO (MV.IOUArray Int Int)
    rankTbl <- MV.newArray (1,n) 0 :: IO (MV.IOUArray Int Int)
    costTbl <- MV.newArray (1,n) 0 :: IO (MV.IOUArray Int Int)
    countTbl <- MV.newArray (1,n) 0 :: IO (MV.IOUArray Int Int)
    forM_ [1..n] $ \i -> do 
        MV.writeArray parent i i
        MV.writeArray rankTbl i 1
    zipWithM_ (\i x -> MV.writeArray costTbl i x) [1..] xs
    let find :: Int -> IO Int
        find a = do
            a' <- MV.readArray parent a
            if a == a' then return a else do
                b <- find a'
                MV.writeArray parent a b
                return b
        unite :: Int -> Int -> IO ()
        unite a b = do
            x <- find a
            y <- find b
            unless (x == y) $ do
                s1 <- MV.readArray rankTbl x
                s2 <- MV.readArray rankTbl y
                c1 <- MV.readArray costTbl x
                c2 <- MV.readArray costTbl y
                d1 <- MV.readArray countTbl x
                d2 <- MV.readArray countTbl y
                if s1 < s2
                    then do
                        MV.writeArray parent x y
                        MV.writeArray costTbl y (c1 + c2)
                        MV.writeArray countTbl y (d1 + d2)
                    else if s2 < s1
                        then do
                            MV.writeArray parent y x
                            MV.writeArray costTbl x (c1 + c2)
                            MV.writeArray countTbl x (d1 + d2)
                        else do 
                            MV.writeArray parent x y
                            MV.writeArray rankTbl x (s1 + 1)
                            MV.writeArray costTbl y (c1 + c2)
                            MV.writeArray countTbl y (d1 + d2)
    let es' = sortOn (\(a,b,y) -> y) es
    ans <- foldM (\acc (a,b,y) -> do
        unite a b
        x <- find a
        c <- MV.readArray costTbl x
        d <- MV.readArray countTbl x
        --  print ("a",a,"b",b,"c",c,"d",d,"y",y, "c>=y",c>=y)
        if c >= y then do
            MV.writeArray countTbl x 0
            return (acc + d + 1)
        else do
            MV.writeArray countTbl x (d+1) 
            return acc) 0 es'
    print (m - ans)
            


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

void err() {
    cout << -1 << endl;
    exit(0);
}

int main()
{
int n;
cin >> n;
ll a,b;
cin >> a >> b;
ll r = 0;
rep(i,n-2) {
    ll x;
    cin >> x;
    r^= x;
}
ll s = a + b;

// {(p,q) | p + q = s, p ^ q = r, 0 <= p <= a}, max(p) = ?
if(s < r || s - r & 1) err();
ll d = (s - r) / 2; // d = p & q
if(d & r || d > a) err(); // ∵min(p) = d

for(int e = 50; e >= 0; --e) {
    if(r & bit(e)) {
        if(d + bit(e) <= a) {
            d += bit(e);
        }
    }
}
if(d > 0) cout << a - d << endl;
else err();
return 0;
}

Measured memory_bytes: 3572
#include<bits/stdc++.h>
using namespace std;
#define pb push_back

int N, M, A, B, i, day, res = 0;
vector<vector<int>> work(100010, vector<int>());
priority_queue<int> profit_q;

int main(){
    cin >> N >> M;
    for(i = 0; i < N; i++){
        cin >> A >> B;
        work[A].pb(B);
    }

    for(day = 1; day <= M; day++){
        for(i = 0; i < work[day].size(); i++) profit_q.push(work[day][i]);
        if(profit_q.empty()) continue;
        res += profit_q.top(); profit_q.pop();
    }

    cout << res << endl;
    return 0;
}




Measured memory_bytes: 5632
/**************************************************************************
Coded by: Saba Karimi(_VINTAGE)
Institution: AIT PUNE
***************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define pb push_back 
#define all(a) a.begin(),a.end()
#define lb lower_bound
#define ub upper_bound
#define pii pair<int,int>
#define ld long double
#define int long long int 
/**************************************************************************/
int mod = 1e9+7;
int mul(int a,int b)
{
    return ((a%mod)*(b%mod))%mod;
}
int add(int a,int b)
{
    return ((a%mod)+(b%mod))%mod;
}
int sub(int a,int b)
{
    return ((a%mod)-(b%mod)+mod)%mod;
}
int power(int a,int b)
{
    int res = 1;
    while(b!=0)
    {
        if(b&1)
            res = mul(res,a);
        b  = b>>1;
        a = mul(a,a);
    }
    return res;
}
int imodulo(int a)
{
    int ans = power(a,mod-2);
    return ans;
}

bool cmp(pii &p1,pii &p2)
{
    if(p1.first<p2.first)
        return true;
    if(p1.first == p2.first)
    {
        return p1.second<=p2.second;
    }
    return false;
}
signed main()
{
    fast;
    int n;
    cin>>n;
    vector<pii> v(n);
    for(int i=0;i<n;i++)
    {
        int a,b;
        cin>>a>>b;
        v[i] = {b,a};
    }
    sort(all(v),cmp);
    int flag = 1;
    int ct = 0;
    for(auto it:v)
    {
        int d = it.first;
        int t = it.second;
        ct+=t;
        if(ct>d)
        {
            flag = 0;
            break;
        }
    }
    if(!flag)
        cout<<"No";
    else cout<<"Yes";
}

Measured memory_bytes: 3328
import java.util.*;
public class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    for(int i = 0;;i++){
      if(n < i * i){
        System.out.println((i-1)*(i-1));
        return;
      }
    }
  }
}


Measured memory_bytes: 23764
#include <iostream>
using namespace std;
int main(void){
    
    int a,b;
    cin >> a >> b;
    
    int max=-10000;
    int sum= a+b;
    if(sum>max)max=sum;
    int min=a-b;
    if(min>max)max=min;
    int aa=a*b;
    if(aa>max)max=aa;
    cout << max;
    
    
    return 0;
}


Measured memory_bytes: 256
a=int(input())
b=int(input())
c=int(input())
d=int(input())
e=int(input())
def time(x):
    return (x+9)//10*10
def last(x):
    return time(x)-x
sum_tim=time(a)+time(b)+time(c)+time(d)+time(e)
ans=sum_tim-max(last(a),last(b),last(c),last(d),last(e))
print(ans)

Measured memory_bytes: 3064
fn read_line() -> String {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s
}

fn read_ints() -> Vec<i32> {
    read_line()
        .split_whitespace()
        .map(|w| w.parse().unwrap())
        .collect()
}

fn main() {
    let n = read_ints()[0];
    let mut a = read_ints();

    let mut alice = 0;
    let mut bob = 0;

    a.sort();
    a.reverse();

    for i in 0..a.len() {
        if i % 2 == 0 {
            alice += a[i];
        } else {
            bob += a[i];
        }
    }

    println!("{}", alice - bob);
}

Measured memory_bytes: 4352
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;

int N, K, ans;

int main()
{
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> N >> K;
	while (N--)
	{
		int t;
		cin >> t;
		if (t >= K) ++ans;
	}
	cout << ans;
}

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

const int INF  = 1e9;
const long long INFLL = 1e18;
const int NMAX = 100005;
const int MMAX = 100005;
const int KMAX = 1005;
const int MOD  = 1e9 + 7;
using namespace std;

// comment to disable debug functions
#define DEBUG

// frequently used macros

#if __cplusplus >= 201103L
#define ALL(v) begin(v),end(v)
#define SORT(v) sort(begin(v), end(v))
#define FIND(v,x) find(begin(v), end(v), (x))
#else
#define ALL(v) (v).begin(),(v).end()
#define SORT(v) sort(v.begin(), v.end())
#define FIND(v,x) find(v.begin(), v.end(), (x))
#endif

#define fi first
#define se second

#define MEMNEXT(from, to) do{ memmove((to), (from), sizeof(from)); \
memset((from), 0, sizeof(from)); } while(0)
#ifdef DEBUG
#define DUMP(x) do{ std::cerr << (#x) << ": " << x << std::endl; }while(0)
#else
#define DUMP(x) do{}while(0)
#endif

// frequent used aliases
typedef long long ll;
typedef pair<int, int> p;
typedef pair<ll, int> lp;
typedef pair<ll, ll> llp;
typedef vector<int> vec;
typedef vector<ll> vecll;
typedef vector<vec> mat;
typedef vector<vecll> matll;

// frequently used constants
static const int di[] = {-1, 0, 1, -1, 1, -1, 0, 1};
static const int dj[] = {-1, -1, -1, 0, 0, 1, 1, 1};

// frequently used structs
struct edge{
  int to,cost;
};

// printf for debug
#ifndef DEBUG
void debug(const char* format, ...){}
#else
void debug(const char* format, ...){
  va_list arg;
  va_start(arg, format);
  vprintf(format, arg);
  va_end(arg);
}
#endif

// dump vector
#ifdef DEBUG
#define DUMPV(v, c) do{       \
  printf("%s: ", #v);         \
  for (int i = 0; i < (c); ++i) \
  {                           \
  cout << (v)[i] << " ";      \
  }                           \
  cout << endl;               \
} while(0)
#else
#define DUMPV(v,c)
#endif

// std::fill of multi dimensions
template<typename A, size_t N, typename T>
void Fill(A (&array)[N], const T &val){
  std::fill( (T*)array, (T*)(array+N), val );
}

// binary search
ll BSearch(ll _begin, ll _end, bool (*f)(ll)){
  ll mid;
  while(_end - _begin > 1LL) {
  mid = _begin + (_end - _begin) / 2LL;
  if(f(mid)) {
    debug("BSearch: f(%d) == true\n", mid);
    _end = mid;
  }
  else
  {
    debug("BSearch: f(%d) == false\n", mid);
    _begin = mid;
  }
  }
  return _end;
}


ll N,M,K,A,B,C,D,E;
int dp[NMAX] = {};

string S;
vec v;

ll ans = {};

void solve(){
  // main algorithm
  for (int i = N; i <= M; ++i)
  {
    auto s = to_string(i);
    reverse(ALL(s));
    if(s == to_string(i))
    {
      ans++;
    }
  }
}
void debug(){
  // output debug information

}
void answer(){
  // output answer
  cout << ans << endl;
}
int main(int argc, char const *argv[])
{
  // operate inputs

  // Fill(dp, -1);
  cin >> N >> M;
  solve();
  #ifdef DEBUG
  debug();
  #endif
  answer();

  return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<deque>
#include<map>
#include<queue>
#include<iomanip>
using namespace std;
#define rep(i,s,n) for(int i = s;i<n;i++)
#define repe(i,s,n) for(int i = s;i<=n;i++)
#define pb push_back
#define fi first
#define se second
typedef long long ll;
typedef pair<int,int>pint;
typedef vector<int>vint;
typedef vector<pint>vpint;
static const ll maxLL = (ll)1 << 62;
const int mod=1000000007;
int dy[]={-1,0,1,0};
int dx[]={0,1,0,-1};

#define int ll

ll c[55][55];

void comb_table(int n){
    rep(i,0,n+1){
        rep(j,0,i+1){
            if(j==0 || j==i){
                c[i][j]=1LL;
            }else{
                c[i][j]=(c[i-1][j-1]+c[i-1][j]);
            }
        }
    }
}

signed main(){
    int n,a,b;
    cin>>n>>a>>b;
    int v[55];
    comb_table(n);
    rep(i,0,n)cin>>v[i];
    sort(v,v+n,greater<int>());
    
    double sum=0;
    rep(i,0,a)sum+=v[i];
    double sum1=sum/a;
    
    int num=0,pos=0;
    rep(i,0,n){
        if(v[i]==v[a-1]){
            num++;
            if(i<a)pos++;
        }
    }
    
    ll cnt=0ll;
    if(pos==a){
        repe(pos,a,b){
            cnt+=c[num][pos];
        }
    }else{
        cnt+=c[num][pos];
    }
    
    cout<< fixed << setprecision(6)<<sum1<<endl;
    cout<< fixed << setprecision(6)<<cnt<<endl;
}

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

using namespace std;

#define int long long
#define all(v) (v).begin(), (v).end()
#define resz(v, ...) (v).clear(), (v).resize(__VA_ARGS__)
#define reps(i, m, n) for(int i = (int)(m); i < (int)(n); i++)
#define rep(i, n) reps(i, 0, n)

template<class T1, class T2> void chmin(T1 &a, T2 b){if(a>b)a=b;}
template<class T1, class T2> void chmax(T1 &a, T2 b){if(a<b)a=b;}

typedef pair<int, int> Pi;
typedef tuple<int, int, int> Ti;
typedef vector<int> vint;

const int inf = 1LL << 55;
const int mod = 1e9 + 7;

struct UnionFind {
  vint data;
  UnionFind(int n):data(n, -1){}
  int find(int x) {
    if(data[x] < 0) return x;
    return data[x] = find(data[x]);
  }
  int size(int x) {
    return -data[find(x)];
  }
  bool same(int x, int y) {
    return find(x) == find(y);
  }
  void unite(int x, int y) {
    x = find(x), y = find(y);
    if(x == y) return;
    if(data[x] < data[y]) swap(x, y);
    data[x] += data[y];
    data[y] = x;
  }
};

signed main()
{
  cin.tie(0);
  ios_base::sync_with_stdio(0);
  cout << fixed << setprecision(12);

  int N;
  cin >> N;
  vint a(N);
  map<int, int> mp;
  rep(i, N) {
    cin >> a[i];
    mp[a[i]] = i;
  }

  UnionFind uf(N);
  int ans = 0;
  for(int i = N; i >= 1; i--) {
    int idx = mp[i];
    ans += a[idx];
    if(idx-1 >= 0 && a[idx] < a[idx-1]) {
      ans += uf.size(idx)*uf.size(idx-1)*a[idx];
      uf.unite(idx, idx-1);
    }
    if(idx+1 < N && a[idx] < a[idx+1]) {
      ans += uf.size(idx)*uf.size(idx+1)*a[idx];
      uf.unite(idx, idx+1);
    }
  }
  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 15872
//#include "bits/stdc++.h"

#define _USE_MATH_DEFINES
#include<cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <deque>
#include <algorithm>
#include <functional>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <iterator>
#include<iomanip>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<complex>

using namespace std;

#define rep(i,a,b) for(int i=(a), i##_len=(b);i<i##_len;i++)
#define rrep(i,a,b) for(int i=(b)-1;i>=(a);i--)
#define all(c) begin(c),end(c)

#define int ll
#define SZ(x) ((int)(x).size())
#define pb push_back
#define mp make_pair

//typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<ll, int> pli;
typedef pair<double, double> pdd;
typedef vector< vector<int> > mat;

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

const int INF = sizeof(int) == sizeof(long long) ? 0x3f3f3f3f3f3f3f3fLL : 0x3f3f3f3f;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-9;

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

	char C;
	cin >> C;
	if ('a' <= C && C <= 'z')cout << 'a' << endl;
	else cout << 'A'<< endl;

	return 0;
}

Measured memory_bytes: 3648
program main
  implicit none
  integer :: n, i
  integer, allocatable :: a(:)
  read(*, *) n
  allocate(a(n))
  read(*, *) (a(i), i = 1, n)

  if (is_possible(a, n)) then
    write(*, "(i0)") cnt(n)
  else
    write(*, "(i0)") 0
  end if

  deallocate(a)
  contains

  pure function is_possible(a, n)
    implicit none
    integer, intent(in) :: n, a(:)
    integer :: i
    integer :: cnt(0:n - 1)
    logical :: is_possible
    is_possible = .true.
    cnt(:) = 0
    do i = 1, n
      cnt(a(i)) = cnt(a(i)) + 1
    end do
    if (mod(n, 2) == 0) then
      do i = n - 1, 1, -2
        if (cnt(i) /= 2) is_possible = .false.
      end do
    else
      do i = n - 1, 2, -2
        if (cnt(i) /= 2) is_possible = .false.
      end do
      if (cnt(0) /= 1) is_possible = .false.
    end if
  end function is_possible

  pure function cnt(n)
    implicit none
    integer, intent(in) :: n
    integer :: i, m, cnt
    integer, parameter :: md = 1000000007
    m = n / 2
    cnt = 1
    do i = 1, m
      cnt = mod(cnt * 2, md)
    end do
  end function cnt
end


Measured memory_bytes: 1536
import scala.io.StdIn._
import scala.collection._

object Main {

  class Sieve(val n: Int){
    private[this] val top = (n - 3) / 2 + 1
    private[this] val cmpsts = new Array[Int]((top >>> 5) + 1)
    private[this] val sqrtLimit = (Math.sqrt(n).toInt - 3) / 2

    def isPrime(ci: Int): Boolean = (cmpsts(ci >>> 5) & (1 << (ci & 31))) == 0
    def notPrime(ci: Int): Unit = cmpsts(ci >>> 5) |= 1 << (ci & 31)

    private def innerLoop(j: Int, p: Int): Unit = {
      if(j <= top){
        notPrime(j)
        innerLoop(j + p, p)
      }
    }

    private def loop(i: Int): Unit = {
      if(i <= sqrtLimit){
        if(isPrime(i)){
          val p = 2 * i + 3
          innerLoop((p * p - 3) >>> 1, p)
        }
        loop(i + 1)
      }
    }

    private def next(i: Int): Int = if((i > top) || isPrime(i)) 2 * i + 3 else next(i + 1)

    def exec: Iterator[Int] = {
      loop(0)
      Iterator.single(2) ++ Iterator.iterate(3)(p => next((p - 1) >>> 1)).takeWhile(_ <= n)
    }
  }

  def loop(s: String){
    if(s != null){
       val Array(n,_*) = s.split(" ").map(_.toInt)
       if(n<2) println(0)
       else if(n==2)println(1)
       else println(new Sieve(n).exec.size)
       loop(readLine)
    }
  }

  def main(args: Array[String]): Unit = loop(readLine)
}

Measured memory_bytes: 65184
x, y = map(int, input().split())
 
ans = (abs(x) + abs(y)) * 2
 
if x < y:
    ans = min(ans, y - x)
 
if -x <= y:
    ans = min(ans, y - (-x) + 1)
 
if x <= -y:
    ans = min(ans, (-y) - x + 1)
 
if -x < -y:
    ans = min(ans, (-y) - (-x) + 2)
 
print(ans)

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

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

    int total = 0;
    for (int i = 0; i < n; ++i){
        total+=i+l;
    }

    if ((0<l && 0<n+l-1)||(l<0&&n+l-1<0)){
        if (abs(l)<abs(n+l-1)){
            cout << total-l << endl;
        }else{
            cout << total-(n+l-1) << endl;
        }
    }else{
        cout << total << endl;
    }
}

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

typedef long long ll;

const int INF = 1e9;
const int MOD = 1e9+7;
const ll LLINF = 1e18;

#define YES(n) cout << ((n) ? "YES" : "NO"  ) << endl
#define Yes(n) cout << ((n) ? "Yes" : "No"  ) << endl
#define ANS(n) cout << (n) << endl

#define FOR(i,a,b) for(int i=(a);i<(b);i++)
#define FORR(i,a,b) for(int i=(a);i>=(b);i--)

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

#define pii pair<int,int>

#define pb(a) push_back(a)
#define mp make_pair

int main()
{
	int n,m;
	cin >> n >> m;
	bool edge[n][n];
	FOR(i,0,n){
		FOR(j,0,n){
			edge[i][j] = false;
		}
	}
	queue<pii> removeEdge;
	FOR(i,0,m){
		int a,b;
		cin >> a >> b;
		removeEdge.push(mp(a-1,b-1));
		edge[a-1][b-1] = true;
		edge[b-1][a-1] = true;
	}
	int ans = 0;
	FOR(i,0,m){
		int a,b;
		a = removeEdge.front().first;
		b = removeEdge.front().second;
		removeEdge.pop();
		edge[a][b] = edge[b][a] = false;
		bool visited[n];
		FOR(j,0,n)visited[j] = false;
		queue<int> visitNode;
		visitNode.push(0);
		visited[0] = true;
		while(!visitNode.empty()){
			int node = visitNode.front();
			visitNode.pop();
			FOR(j,0,n){
				if(visited[j])continue;
				if(edge[node][j]){
					visitNode.push(j);
					visited[j] = true;
				}
			}
		}
		bool isConnected = true;
		FOR(j,0,n){
			if(!visited[j]){
				isConnected = false;
				break;
			}
		}
		if(!isConnected)ans++;
		edge[a][b] = edge[b][a] = true;
	}
	ANS(ans);
	return 0;
}


Measured memory_bytes: 256