akhauriyash/Code-Regression huggingface dataset:
<?php
fscanf(STDIN, "%s", $S);
fscanf(STDIN, "%d", $K);

$first1 = 0;
if (preg_match("/^1+/", $S, $reg)) {
    $first1 = strlen($reg[0]);
};
if ($first1 >= $K) {
    echo "1";
} else {
    $arr = str_split($S);
    $cnt = count($arr);
    for ($i = 0; $i < $cnt; $i++) {
        if ($arr[$i] !== "1") {
            echo $arr[$i];
            break;
        }
    }
}

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


using namespace std;
typedef long long ll;

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

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

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

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

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

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

int main(){
  int n,h;
  cin>>n>>h;
  int a[n],b[n];
  for(int i = 0; i < n; i++) cin>>a[i]>>b[i];
  sort(a,a+n);
  sort(b,b+n);
  reverse(b,b+n);
  int cnt=0;
  for(int i = 0; i < n; i++){
    if(b[i]>=a[n-1]){
      h-=b[i];
      cnt++;
      if(h<=0){
        cout<<cnt<<endl;
        return 0;
    }
    }
    else break;
  }
 
  cnt+=(h-1)/a[n-1]+1;
  cout<<cnt<<endl;
  

  return 0;
}


Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define debug(x) cerr << #x << ": " << x << '\n';
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int a, b;
  cin >> a >> b;
  cout << max(a - 2 * b, 0) << '\n';
}


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

class Program{
	static void Main(){
		int n=int.Parse(Console.ReadLine());
		var dict=new Dictionary<string,int>();
		var Max=0;
		for(int i=0;i<n;i++){
			string s=Console.ReadLine();
			if(!dict.ContainsKey(s))dict[s]=0;
			dict[s]++;
			Max=Math.Max(Max,dict[s]);
		}
		foreach(var s in dict.Where(x=>x.Value==Max).OrderBy(x=>x.Key)){
			Console.WriteLine(s.Key);
		}
	}
}

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

long modFact(long x, long mod);

int main() {
    const long MOD = 1000000007;
    long n, m, ans = 0;
    cin >> n >> m;
    if(n == m) ans = 2 * modFact(n, MOD) * modFact(m, MOD) % MOD;
    else if(n + 1 == m || n == m + 1) ans = modFact(n, MOD) * modFact(m, MOD) % MOD;
    cout << ans << endl;
}

long modFact(long x, long mod) {
    if(x == 0 || x == 1) return 1;
    return x * modFact(x - 1, mod) % mod; 
}

Measured memory_bytes: 3328
#ifndef VS
#include<bits/stdc++.h>
#endif

using namespace std;
typedef long long LL;

#ifdef BTK
#define DEBUG if(1)
#else
#define CIN_ONLY if(1)
struct cww {cww() {CIN_ONLY{ios::sync_with_stdio(false); cin.tie(0);}}
}star;
#define DEBUG if(0)
#endif

#define ALL(v) (v).begin(),(v).end()
#define REC(ret, ...) std::function<ret (__VA_ARGS__)>
template <typename T>inline bool chmin(T &l, T r){bool a = l>r; if (a)l = r; return a;}
template <typename T>inline bool chmax(T &l, T r){bool a = l<r; if (a)l = r; return a;}
template <typename T>istream& operator>>(istream &is, vector<T> &v){for (auto &it : v)is >> it;return is;}

class range {private: struct I { int x; int operator*() { return x; }bool operator!=(I& lhs) { return x<lhs.x; }void operator++() { ++x; } }; I i, n;public:range(int n) :i({ 0 }), n({ n }) {}range(int i, int n) :i({ i }), n({ n }) {}I& begin() { return i; }I& end() { return n; }};
int N;
int a[212345];
int b[212345];
int c[212345];
LL ds[112345];
LL cs[112345];
LL dt[112345];
LL ct[112345];
typedef vector<int> V;
typedef vector<V> VV;
VV g;
constexpr LL INF = 1e18;
constexpr int mod = 1e9 + 7;
typedef pair<LL, int> P;
priority_queue<P> que;
void dijkstra(int s,LL* d,LL* cnt) {
	d[s] = 0;
	cnt[s] = 1;
	que.push({ d[s],s });
	while (que.size()) {
		int v; LL cost;
		tie(cost, v) = que.top(); que.pop();
		cost = -cost;
		if (d[v] > cost)continue;
		for (int e : g[v]) {
			int u = v ^ a[e] ^ b[e];
			LL nxtcost = cost + c[e];
			if (chmin(d[u], nxtcost)) {
				cnt[u] = 0;
				que.push({ -d[u],u });
			}
			if (d[u] == nxtcost) {
				cnt[u] += cnt[v];
				if (cnt[u] >= mod)cnt[u] -= mod;
			}
		}
	}
}
int main() {
	int S, T, M;
	cin >> N >> M >> S >> T;
	g = VV(N);
	S--; T--;
	for (int i : range(M)) {
		cin >> a[i] >> b[i] >> c[i];
		a[i]--; b[i]--;
		g[a[i]].push_back(i);
		g[b[i]].push_back(i);
	}
	fill(ds, ds + N, INF);
	fill(dt, dt + N, INF);
	fill(cs, cs + N, 0ll);
	fill(ct, ct + N, 0ll);
	dijkstra(S, ds, cs);
	dijkstra(T, dt, ct);
	LL ret = cs[T] * cs[T] % mod;
	for (int i : range(N)) {
		if (ds[i] + dt[i] == ds[T] && ds[i] == dt[i]) {
			LL k = cs[i] * ct[i] % mod;
			ret += mod - k*k%mod;
		}
	}
	LL half = (ds[T] + 1) / 2;
	for (int i : range(M)) {
		int u = a[i], v = b[i];
		if (ds[u] + dt[v] + c[i] == ds[T] && ds[u] < half&&dt[v] < half) {
			LL k = cs[u] * ct[v] % mod;
			ret += mod-k*k%mod;
		}
		swap(u, v);
		if (ds[u] + dt[v] + c[i] == ds[T] && ds[u] < half&&dt[v] < half) {
			LL k = cs[u] * ct[v] % mod;
			ret += mod-k*k%mod;
		}
	}
	cout << ret%mod << endl;
	return 0;
}


Measured memory_bytes: 14324
// Input macro
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! stdin {
    () => {{
        use std::io::Read;
        let mut s = String::new();
        std::io::stdin().read_to_string(&mut s).unwrap();
        s
    }};
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// Test Code
macro_rules! test {
    ($($input:expr => $output:expr),* $(,)*) => {
        #[test]
        fn solve_test() {
            $(
                assert_eq!(solve($input), $output);
            )*
        }
    };
}

test! {
    "3" => "6",
    "10" => "3628800",
    "100000" => "457992974",
}

fn main() {
    println!("{}", solve(&stdin!()));
}

fn solve(src: &str) -> String {
    input! {
        source = src,
        n: u64,
    }

    let mut num = 1;

    for i in 2..n + 1 {
        num = (num * i) % (1_000_000_000 + 7);
    }

    num.to_string()
}

Measured memory_bytes: 4352
from math import gcd


class Eratosthenes(): # エラトステネスの篩
    def __init__(self, N): # 素数リスト生成 O(n*log(log n))
        self.fact = [i for i in range(N + 1)]
        for i in range(2, int(N**0.5) + 1):
            if self.fact[i] < i:
                continue
            for j in range(i * 2, N + 1, i):
                self.fact[j] = i
        self.prime_list = [i for i, pi in enumerate(self.fact[2:], 2) if pi == i]


    def factor(self, NUM):  # 高速素因数分解 O(log num)
        PRIME = set()
        for p in self.prime_list:
            if p * p > NUM:
                break
            while NUM % p == 0:
                NUM //= p
                PRIME.add(p)
        if NUM > 1:
            PRIME.add(NUM)
        return PRIME


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

ans = 0
for ai in a:
    ans = gcd(ans, ai)
if ans != 1:
    print('not coprime')
    exit()

era = Eratosthenes(max(a))
num = set()
for ai in a:
    prime = era.factor(ai)
    if len(prime & num) > 0:
        print('setwise coprime')
        break
    num |= prime
else:
    print('pairwise coprime')


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

int main()
{
    vector<double> polygonSides;
    int sides;
    double L;

    cin >> sides;
    while(sides--)
    {
        cin >> L;
        polygonSides.push_back(L);
    }

    sort(polygonSides.begin(), polygonSides.end(),greater<double>());

    double condition = 0;
    for(int i = 1; i <= polygonSides.size(); ++i)
    {
        condition += polygonSides[i];
    }

    if(polygonSides[0] < condition)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
int n,a,b;
inline int read(){
    int res=0,f_f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-') f_f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') res=(res<<3)+(res<<1)-'0'+ch,ch=getchar();
    return res*f_f;
}
int main(){
    n=read(),a=read(),b=read();
    if(a>b) printf("0\n");
    else if(n==1&&a!=b) printf("0\n");
    else printf("%lld\n",1ll*(n-1)*b+a-1ll*(n-1)*a-b+1);
    return 0;
}

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

int main() {
    int n,x;
    cin >> n >> x;
    vector<int> m(n);
    for(int i=0;i<n;i++){
        cin >> m.at(i);
        x -= m.at(i);
    }
    sort(m.begin(),m.end());
    cout << (x/m.at(0))+n << endl;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define f first
#define s second
#define pb push_back
#define fix  cout<<std::fixed;
#define mk make_pair
#define time  cerr<< '\n' << "Time elapsed :" << clock() * 1000.0 / CLOCKS_PER_SEC << " ms\n" ;
#define IOS             ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
int main()
{  
 ll n;cin>>n;
 ll a[n];
 for(int i=0;i<n;i++)
        cin>>a[i];

        ll dp[n];

        for(int i=0;i<n;i++)
        {
            if(i==0)dp[i]=0;
            else if(i==1)dp[i]=abs(a[i]-a[i-1]);
            else
                dp[i]=min(abs(a[i]-a[i-1])+dp[i-1],abs(a[i]-a[i-2])+dp[i-2]);
            

        }   cout<<dp[n-1];

}

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

int main()
{
  int N, M;
  int ans = -1;
  cin >> N >> M;
  vector<pair<int, char>> sc(M);
  for (int i = 0; i < M; ++i) {
    cin >> sc[i].first >> sc[i].second;
  }
  for (int i = pow(10, N-1)-1, ma = pow(10, N); i < ma; ++i) {
    bool flag = 1;
    string s = to_string(i);
    if (int(s.size()) != N) continue;
	for (int j = 0; j < M; ++j) {
	  if (s[sc[j].first-1] != sc[j].second) {flag = 0; break;}
    }
    if (flag) {ans = i; break;}
  }
  cout << ans << "\n";
}

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

int main()
{
    //freopen("input.txt","r", stdin);
    //freopen("output.txt","w",stdout);
    int n; cin>>n;
    int a[n];
    for(int i=0;i<n;i++) cin>>a[i];

    sort(a,a+n);
    int ans =1;
    for(int i=1;i<n;i++)
    {
       if(a[i]!=a[i-1]) ans++;
    }

    cout<<ans;
}

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

int main() {
	int h[10];
	int rank[3];
	for(int i = 0; i < 3; i++){
		rank[i] = 0;
	}
	for(int i = 0; i < 10; i++){
		cin >> h[i];
	}
	for(int i = 0; i < 10; i++){
		if(h[i] >= rank[0]){
			rank[2] = rank[1];
			rank[1] = rank[0];
			rank[0] = h[i];
		} else if(h[i] >= rank[1]) {
			rank[2] = rank[1];
			rank[1] = h[i];
		} else if(h[i] >= rank[2]){
			rank[2] = h[i];
		}
	}
	for(int i = 0; i < 3; i++){
		cout << rank[i] << endl;
	}
	return 0;
}

Measured memory_bytes: 1164
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  long long N;
  cin >> N;
  
  vector<long long> A(N);
    
  for (long long i=0; i<N; i++) {
    cin >> A.at(i); 
  }
  
  sort(A.begin(),A.end());
  
  long long S;
  S = 1LL;
  
  if (A.at(0) == 0) {
    cout << 0 << endl; 
  }
  else {
    for (long long i=0; i<N; i++) {
      if (1000000000000000000LL/S>=A.at(i)){
        S = S*A.at(i);
      }
      else {
        S = 2000000000000000000LL;
        break; 
      }   
    }
      
    if (S<= 1000000000000000000LL) {
      cout << S << endl;  
    }
    else {
      cout << -1 << endl;  
    }
    
  }   
} 
  
 

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

using namespace std;

int N, Q;
vector<int> DataA, DataB;

int solve(int same) {
	int x, y;

	for (int i = 0; i < Q; ++i) {
		cin >> x >> y;
		--x;
		--y;
		if (DataA[x] == DataB[x]) {
			--same;
		}
		if (DataA[y] == DataB[y]) {
			--same;
		}
		if (DataA[x] == DataB[y]) {
			++same;
		}
		if (DataA[y] == DataB[x]) {
			++same;
		}
		swap(DataA[x], DataA[y]);
		if (same == N) {
			return (i + 1);
		}
	}

	return -1;
}

int main() {
	int a, same;

	same = 0;
	cin >> N;
	for (int i = 0; i < N; ++i) {
		cin >> a;
		DataA.push_back(a);
		DataB.push_back(a);
	}
	sort(DataB.begin(), DataB.end());
	for (int i = 0; i < N; ++i) {
		if (DataA[i] == DataB[i]) {
			++same;
		}
	}
	if (same == N) {
		cout << "0" << endl;
		return 0;
	}
	cin >> Q;
	cout << solve(same) << endl;

	return 0;
}


Measured memory_bytes: 6096
#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
typedef long long ll;
using namespace std;
ll n,k,i,hz,te,has,p[101010];
char a[101010];
pair<ll,ll> A[101010];
int main()
{
	ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
	cin>>n>>k;
	for(i=1;i<=n;i++)
		cin>>a[i];
	for(i=1;i<=n;i++)
	{
		hz++;
		if(i==n||a[i]!=a[i+1])
		{
			A[++te]=mp(a[i],hz);
			//cout<<A[te].se<<"\n";
			hz=0;
		}
	}
	for(i=1;i<=te;i++)p[i]=p[i-1]+A[i].se;
	for(i=1;i<=te;i++)
	{
		ll R=min(te,i+k*2);
		if(A[i].fi=='0')R=min(te,i+k*2-1);
		has=max(has,p[R]-p[i-1]);
	}
	cout<<has<<"\n";
}


Measured memory_bytes: 2688
d, n = map(int, input().split())
if d==0:
  if n == 100:
    ans = 101
  else:
    ans = n
elif d==1:
  if n == 100:
    ans = 10100
  else:
    ans = n*100
elif d==2:
  if n == 100:
    ans = 1010000
  else:
    ans = n*10000
print(ans)

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

int n,m;
bool u[10]={false};
vector<int> g[10];
int dfs(int v,int uv);

int main(void){
  int i,a,b;
  cin >> n >> m;
  for (i=0;i<m;i++){
    cin >> a >> b;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  u[1]=true;
  cout << dfs(1,1) << endl;
  return 0;
}

int dfs(int v,int uv){
  int i,ret=0;
  if (uv==n) return 1;
  for (i=0;i<g[v].size();i++){
    if (u[g[v][i]]) continue;
    u[g[v][i]]=true;
    ret+=dfs(g[v][i],uv+1);
    u[g[v][i]]=false;
  }
  return ret;
}

Measured memory_bytes: 256
/// 2222 by 1 february, thx

#include<bits/stdc++.h>
#pragma GCC optimize("O3")
using namespace std;
int n, dp[100002][5];
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> n;
    for(int i = 1; i <= n; ++i)
    {
        int a, b, c;
        cin >> a >> b >> c;
        dp[i][1] = max(dp[i-1][2], dp[i-1][3]) + a;
        dp[i][2] = max(dp[i-1][1], dp[i-1][3]) + b;
        dp[i][3] = max(dp[i-1][2], dp[i-1][1]) + c;
    }
    cout << max(dp[n][1], max(dp[n][2], dp[n][3]));
    return 0;
}



Measured memory_bytes: 2176
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <string>
#include <queue>
#include <stack>

using namespace std;

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

const ll mod = 1000000007;

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

  int k, n;
  cin >> k >> n;
  vector<int> a(n);
  for (auto &x: a) cin >> x;

  a.push_back(a[0] + k);
  int ans = 1000000007;
  for (int i = 0; i < n; i++) {
    int d = k - (a[i+1] - a[i]);
    if (d < ans) ans = d;
  }

  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 1792
#include<bits/stdc++.h>
#define eps 1e-9
#define MOD 1000000007;
#define INV_10 299473306;
using namespace std;
int main()
{
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	string s;
	cin >> s;
	bool ok=false;
	for(int i = 0; i < s.length(); i++)
		if(s[i]=='7')
			ok=true;
	cout << (ok? "Yes\n":"No\n");
}

Measured memory_bytes: 3652
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;

int p[410][4];
int v[2][4];

map<vector<int>, int> cnt;
map<vector<int>, int> qcnt;

vector<int> norm(int a, int b, int c, int d){
  vector<int> v0 = {a, b, c, d}, v1 = {b, c, d, a}, v2 = {c, d, a, b}, v3 = {d, a, b, c};
  return min(v0, min(v1, min(v2, v3)));
}
vector<int> norm(int id){
  return norm(p[id][0], p[id][1], p[id][2], p[id][3]);
}

int main(){
  int N; scanf("%d", &N);
  for(int i = 0; i < N; i++){
    for(int j = 0; j < 4; j++) scanf("%d", &p[i][j]);
    cnt[norm(i)]++;
  }

  long long ans = 0;

  for(int A = 0; A < N; A++){ // dir = 0
    for(int i = 0; i < 4; i++) v[0][i] = p[A][i];
    cnt[norm(A)]--;

    for(int B = 0; B < N; B++){
      if(A == B) continue;
      cnt[norm(B)]--;

      for(int BD = 0; BD < 4; BD++){
        for(int i = 0; i < 4; i++) v[1][i] = p[B][(BD + i) % 4];

        qcnt.clear();

        qcnt[norm(v[0][3], v[0][2], v[1][2], v[1][1])]++;
        qcnt[norm(v[0][2], v[0][1], v[1][3], v[1][2])]++;
        qcnt[norm(v[0][1], v[0][0], v[1][0], v[1][3])]++;
        qcnt[norm(v[0][0], v[0][3], v[1][1], v[1][0])]++;

        long long r = 1;

        for(auto &pp : qcnt){
          int c = pp.second, cc = cnt[pp.first];
          int m = 1;

          if(pp.first[0] == pp.first[1] && pp.first[1] == pp.first[2] && pp.first[2] == pp.first[3]) m = 4;
          else if(pp.first[0] == pp.first[2] && pp.first[1] == pp.first[3]) m = 2;

          for(int j = 0; j < c; j++) r *= (cc - j) * m;
        }

        ans += r;
      }

      cnt[norm(B)]++;
    }
    cnt[norm(A)]++;
  }

  printf("%lld\n", ans / 6);
  return 0;
}

Measured memory_bytes: 139904
def solve(li):
    for i in range(n):
        if li[i] == 0:
            continue
        else:
            for name, honest in L[i]:
                if li[name-1] != honest:
                    return 0
    else:
        return li.count(1)

n = int(input())
L = []
for _ in range(n):
    a = int(input())
    A = [list(map(int, input().split())) for _ in range(a)]
    L.append(A)
ans = 0
for i in range(2 ** n):
    li = [0] * n
    for j in range(n):
        if ((i >> j) & 1 != 0):
            li[j] = 1
    ans = max(ans, solve(li))
print(ans)


Measured memory_bytes: 3064
#include <iostream>
#include <vector>

int main(void){
  int N;

  std::cin>>N;

  std::vector<int64_t> A(N+1),B(N);

  for(int i=0;i<N+1;i++){
    std::cin >> A[i];
  }

  for(int i=0;i<N;i++){
    std::cin >> B[i];
  }
  
  int64_t s=0;
  for(int i=0;i<N;i++){
    for(int j=0;j<2;j++){
      if(B[i] > A[i+j]){
	s+=A[i+j];
	B[i]-=A[i+j];
	A[i+j]=0;
      }else{
	s+=B[i];
	A[i+j]-=B[i];
	B[i]=0;
      }
    }
  }

  std::cout << s;

  return 0;
}


Measured memory_bytes: 1792
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline

D = int(input())
C = list(map(int,input().split()))
S = [list(map(int,input().split())) for _ in range (D)]
M = 26
INF = 10**20

ans = [0]*D
lasts = [0]*(M+1)

for i in range(D):
    score = -INF
    contest = 0
    for m in range(1,M+1):
        cur = S[i][m-1]
        cur -= C[m-1]*(i+1-lasts[m])
        if cur>score:
            score = cur
            contest = m
    ans[i] = contest
    lasts[contest] = i

for a in ans:
    print(a)

Measured memory_bytes: 68508
#include <bits/stdc++.h>
using namespace std;
#define FOR(i, x, y) for (int i = x; i < y; i++)
#define FORN(i, x, y) for (int i = x; i <= y; i++)
#define DEC(i, x, y) for (int i = x; i >= y; i--)
#define scan1(X) scanf("%d", &X)
#define scan2(X, Y) scanf("%d%d", &X, &Y)
#define scan3(X, Y, Z) scanf("%d%d%d", &X, &Y, &Z)
#define scan4(X, Y, Z, W) scanf("%d%d%d%d", &X, &Y, &Z, &W)
#define scanl1(X) scanf("%lld", &X);
#define scanl2(X, Y) scanf("%lld%lld", &X, &Y)
#define scanl3(X, Y, Z) scanf("%lld%lld%lld", &X, &Y, &Z)
#define scanl4(X, Y, Z, W) scanf("%lld%lld%lld%lld", &X, &Y, &Z, &W)
#define print1(X) printf("%d\n", X);
#define print2(X, Y) printf("%d %d\n", X, Y);
#define print3(X, Y, Z) printf("%d %d %d\n", X, Y, Z);
#define print4(X, Y, Z, W) printf("%d %d %d %d\n", X, Y, Z, W);
#define printl1(X) printf("%lld\n", X);
#define printl2(X, Y) printf("%lld %lld\n", X, Y);
#define printl3(X, Y, Z) printf("%lld %lld %lld\n", X, Y, Z);
#define printl4(X, Y, Z, W) printf("%lld %lld %lld %lld\n", X, Y, Z, W);
#define max3(X, Y, Z) max(X, max(Y, Z))
#define max4(X, Y, Z, W) max(max(X, Y), max(Z, W))
#define min3(X, Y, Z) min(X, min(Y, Z))
#define min4(X, Y, Z, W) min(min(X, Y), min(Z, W))
#define popcount(X) __builtin_popcount(X)
#define all(x) x.begin(), x.end()
#define size(X) (int)X.size()
#define mp make_pair
#define pb push_back
#define fr first
#define sc second
#define lc(x) 2 * x
#define rc(x) 2 * x + 1
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
typedef pair<ld, ld> pldld;
const long long l_inf = numeric_limits<long long>::max();
const long long l_ninf = numeric_limits<long long>::min();
const int inf = numeric_limits<int>::max();
const int ninf = numeric_limits<int>::min();
const double pi = 1.00 * acos(-1.00);
const double eps = 1e-8;
void cio(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
}
ll gcd(ll a, ll b){
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) { return (a * (b / gcd(a, b))); }
int sq( int x ) {return x * x;}
////////////////////////////////////////////////////////////////////Header
const int MOD = 1e9 + 7;
const int maxn = 1004;
int a[maxn][maxn];
int dp[maxn][maxn];
int n, m;

int add ( int a, int b ) { return ( a + b ) % MOD; }

int main () {
    scan2(n, m);
    FORN(i, 1, n) FORN(j, 1, m) {
        char ch;
        scanf(" %1c", &ch);
        if ( ch == '.' ) a[i][j] = 1;
        else a[i][j] = 0;
    }
    dp[1][1] = 1;
    FORN(i, 1, n) FORN(j, 1, m) {
        if ( !a[i][j] ) dp[i][j] = 0;
        else {
            if ( i >= 2 ) dp[i][j] = add(dp[i][j], dp[i-1][j]);
            if ( j >= 2 ) dp[i][j] = add(dp[i][j], dp[i][j-1]);
        }
    }
    print1(dp[n][m]);
}

Measured memory_bytes: 11552
#if defined(__GNUC__)
#include <bits/stdc++.h>
#define __int32 __int32_t
// __GNUC__
#else
#include "bits/stdc++.h"
#endif
using namespace std;

#define int long long

#define itn __int32
#define REP(i, n) for(itn (i) = 0; (i) < (n); ++(i))
#define REP2(i, x, n) for(itn (i) = x; (i) < (n); ++(i))
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define SORT(x) std::sort(ALL(x))
#define RSORT(x) std::sort(ALL(x), greater<decltype(x)::value_type>())
#define RSORT2(x, T) std::sort(ALL(x), greater<T>())
#define REVERCE(x) std::reverce(ALL(x))
#define ACM(x, y) std::accumulate(ALL(x), y)

#define INT_POW(x, y) [](int a, int b) -> int {int c = a; REP(i, b - 1){c *= a;} return c;}(x, y)
#define INT_POWM(x, y, m) [](int a, int b, int m) -> int {int c = a; REP(i, b - 1){c *= a; c %= m;} return c;}(x, y, m)
#define FCT(x) [](int a) -> int {int r = 1; REP(i, a){r *= i;} return r;}(x)

// デバッグ用
#define PUT_LIST(x, y) std::copy(ALL(x), std::ostream_iterator<decltype(x)::value_type>(std::cout, y))

itn main() {
	std::ios::sync_with_stdio(false);

	int n;

	cin >> n;

	vector<int> x(n);

	REP(i, n) {
		cin >> x[i];
	}

	int p = ACM(x, 0) / n;

	int res1 = 0;
	int res2 = 0;

	REP(i, n) {
		int l = x[i] - p;
		res1 += l * l;
		res2 += (l - 1) * (l - 1);
	}

	cout << min(res1, res2);

	return 0;
}


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

int main() {
  long long N,x;
  cin >> N;
  vector<vector<long long>> D(N, vector<long long>(2));
  for (long long i=0;i<N;i++) {
    for (long long j=0;j<2;j++) {
      cin >> D.at(i).at(j);
    }
  }
  x=0;
  for (long long i=0;i<N;i++) {
    if (D.at(i).at(0)==D.at(i).at(1)) {
      x++;
      if (x==3) {
        break;
      }
    }
    if (D.at(i).at(0)!=D.at(i).at(1)) {
      x=0;
    }
  }
  if (x==3) {
    cout << "Yes" << endl;
  }
  if (x!=3) {
    cout << "No" << endl;
  }
}

Measured memory_bytes: 3632
#include <iostream>
#include <string>

using namespace std;

void solve()
{
	string str;
	getline(cin, str);
	int n = str.size();
	int count = 0;
	if(str[0] == ' ')
	{
		cout << 0 << endl;
		return;
	}
	if(n % 2)
	{
		if(str[n / 2] != 'i' && str[n / 2] != 'w')
		{
			count++;
		}
		for(int i = 0; i < n / 2; ++i)
		{
			if(str[i] == 'i' && str[n - i - 1] != 'i' ||
			   str[i] == 'w' && str[n - i - 1] != 'w' ||
			   str[i] == '(' && str[n - i - 1] != ')' ||
			   str[i] == ')' && str[n - i - 1] != '(')
			{
				count++;
			}
		}
	}
	else
	{
		if(str[n / 2 - 1] == 'i' && str[n / 2] != 'i' ||
		   str[n / 2 - 1] == 'w' && str[n / 2] != 'w' ||
		   str[n / 2 - 1] == '(' && str[n / 2] != ')' ||
		   str[n / 2 - 1] == ')' && str[n / 2] != '(')
		{
			count++;
		}
		for(int i = 0; i < n / 2 - 1; ++i)
		{
			if(str[i] == 'i' && str[n - i - 1] != 'i' ||
			   str[i] == 'w' && str[n - i - 1] != 'w' ||
			   str[i] == '(' && str[n - i - 1] != ')' ||
			   str[i] == ')' && str[n - i - 1] != '(')
			{
				count++;
			}
		}
	}
	cout << count << endl;
}

int main()
{
	solve();
	return(0);
}

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

vector<vector<int>> a(100000);
int info[100000][2];
int k[100000], v;

void mktree(int par, int z, int dep) {
	info[z][1] = dep;
	info[z][0] = par;
	dep++;
	for (int i = 0; i < k[z]; i++) {
		mktree(z, a[z][i], dep);
	}
}

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

	int N; cin >> N;
	int id;
	int su = 0;
	for (int i = 0; i < N; i++) {
		cin >> id;
		cin >> k[id];
		for (int j = 0; j < k[id]; j++) {
			cin >> v;
			a[id].push_back(v);
			su += v;
		}
	}
	int node = N * (N - 1) / 2 - su;
	mktree(-1, node, 0);
	if (N == 1) {
		cout << "node " << 0 << ": parent = " << -1 << ", depth = " << 0 << ", root, []" << endl;
		return 0;
	}
	for (int i = 0; i < node; i++) {
		cout << "node " << i << ": parent = " << info[i][0] << ", depth = " << info[i][1] << ", ";
		if (k[i] == 0)cout << "leaf, []" << endl;
		else {
			cout << "internal node, [";
			for (int j = 0; j < k[i] - 1; j++) {
				cout << a[i][j] << ", ";
			}
			cout << a[i][k[i] - 1];
			cout << "]" << endl;
		}
	}
	cout << "node " << node << ": parent = " << info[node][0] << ", depth = " << info[node][1] << ", ";
	cout << "root, [";
	for (int j = 0; j < k[node] - 1; j++) {
		cout << a[node][j] << ", ";
	}
	cout << a[node][k[node] - 1];
	cout << "]" << endl;
	for (int i = node + 1; i < N; i++) {
		cout << "node " << i << ": parent = " << info[i][0] << ", depth = " << info[i][1] << ", ";
		if (k[i] == 0)cout << "leaf, []" << endl;
		else {
			cout << "internal node, [";
			for (int j = 0; j < k[i] - 1; j++) {
				cout << a[i][j] << ", ";
			}
			cout << a[i][k[i] - 1];
			cout << "]" << endl;
		}
	}

}


Measured memory_bytes: 6964
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int i, j, n, team1, team2, score1, score2;
		n = sc.nextInt();
		int [] Team = new int[n+1];
		int [] Rank = new int[n+1];
		for(i = 0; i < n * (n - 1) / 2; i++){
			team1 = sc.nextInt();
			team2 = sc.nextInt();
			score1 = sc.nextInt();
			score2 = sc.nextInt();
			if(score1 > score2){
				Team[team1] = Team[team1] + 3;
			}else if(score1 == score2){
				Team[team1] = Team[team1] + 1;
				Team[team2] = Team[team2] + 1;
			}else{
				Team[team2] = Team[team2] + 3;
			}
		}
		for(i = 1; i < n + 1; i++){
			Rank[i] = 1;
			for (j = 1; j < n + 1; j++) {
				if (Team[i] < Team[j]) {
				Rank[i]++;
				}
			}
			System.out.println(Rank[i]);
		}
	}
}

Measured memory_bytes: 41968
/*input
4 9
3 3 3 3
*/

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <math.h>
#include <iomanip>
#include <utility>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <algorithm>

using namespace std;
using ll = long long;
using ld = long double;

ll MOD = 1000000007;
const int SINF = 1000000009;
const ll INF =  1000000000000000018;

#define sp          cout << " "
#define nl          cout << "\n"
#define inv(a)      powr((a), (MOD - 2))
#define all(c)      (c).begin(),(c).end()
#define rep(i,a,b)  for(ll i = (a); i < (b); i ++)
#define prec(n)     cout << fixed << setprecision(n)
#define PI          3.14159265358979323846264338327951
#define ifalse      ios_base::sync_with_stdio(false), cin.tie(NULL)

template<typename T> void toInt(string s, T &a) { istringstream(s) >> a; }
ll gcd(ll a, ll b) { ll t; while(a) { t = a; a = b%a; b = t; } return b; }
ll sub(ll a, ll b) { a -= b; a = (a + MOD) % MOD; return a; }
ll mul(ll a, ll b) { return ((a % MOD) * (b % MOD)) % MOD; }
ll add(ll a, ll b) { a += b; a %= MOD; return a; }
ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); }

ll powr(ll a, ll b) {
  ll x = 1LL;
  while(b) {
    if(b & 1) x = mul(x, a);
    a = mul(a, a), b >>= 1;
  }
  return x;
}

bool check(ll n)
{
  if(n == 1) return 0;
  if(n == 2 or n == 3) return 1;
  if(n%2 == 0 or n%3 == 0) return 0;
  for(ll i = 5; i*i <= n; i += 6) if(n%i == 0 or n % (i+2) == 0) return 0;
  return 1;
}

/*********************************START**********************************/
const int N = 100005;

int main()
{
  ifalse;
  int n, x;
  cin >> n >> x;
  vector < int > v(n);
  for(auto &x: v) {
    cin >> x;
  }

  int ans = 1, d = 0;
  for(int i = 0; i < n; i ++) {
    d += v[i];
    if(d <= x) {
      ans ++;
    } else {
      break;
    }
  }
  cout << ans, nl;
  return 0;
}

Measured memory_bytes: 256
/*====Corycle====*/
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<complex>
#include<cstdio>
#include<vector>
#include<cmath>
#include<ctime>
#include<stack>
#include<queue>
#include<map>
#define ll long long
using namespace std;
const int inf=0x3f3f3f3f;
const int N=1e5+5;
int read(){
	int s=0,f=1;char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){s=s*10+c-'0';c=getchar();}
	return s*f;
}
int n;
char s[N];
int main(){
//	freopen("_.in","r",stdin);
//	freopen("_.out","w",stdout);
	scanf("%s",s+1);n=strlen(s+1);
	for(int i=1;i<=n-1;i++)if(s[i]==s[i+1]){printf("%d %d\n",i,i+1);return 0;}
	for(int i=1;i<=n-2;i++)if(s[i]==s[i+1]||s[i+1]==s[i+2]||s[i]==s[i+2]){printf("%d %d\n",i,i+2);return 0;}
	printf("-1 -1\n");
	return 0;
}

Measured memory_bytes: 3880
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define rep(i, n) for(int i=0; i<(n); ++i)
#define REP(i, d, n) for(int i=(d); i<(n); ++i)
#define all(v) v.begin(), v.end()
using P = pair<int, int>;

signed main() {

    int n, k;
    cin >> n >> k;
    vector<int> d(k), snuke(n);
    vector<vector<int>> a(k);
    rep(i, k){
        cin >> d[i];
        a[i].resize(d[i]);
        rep(j, d[i]){
            cin >> a[i][j];
            snuke[a[i][j]-1]++;
        }
    }

    int ans = 0;
    rep(i, n){
        if(snuke[i] == 0){
            ans++;
        }
    }
    cout << ans << endl;

    return 0;
}


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

int main(int argc, char const *argv[]) {
    string N;
    cin >> N;

    char last = N[N.size()-1];
    if (last == '2' || last == '4' || last == '5' || last == '7' || last == '9') {
        cout << "hon" << endl;
    }else if (last == '0' || last == '1' || last == '6' || last == '8') {
        cout << "pon" << endl;
    }else{
        cout << "bon" << endl;
    }

    return 0;
}


Measured memory_bytes: 3600
#include<set>
#include<map>
#include<deque>
#include<queue>
#include<stack>
#include<cmath>
#include<ctime>
#include<bitset>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<climits>
#include<complex>
#include<iostream>
#include<algorithm>
#define ll long long
#define __ %=Mod
using namespace std;

const ll Mod = 1e9+7;
const int maxn = 4100;

int n,m;
ll f[2][maxn];
ll solve(const int u)
{
	int now=0; memset(f,0,sizeof f);
	for(int i=0;i<=u;i++) f[now][i]=1ll;
	for(int i=1;i<=m;i++)
	{
		now=!now;
		for(int j=0;j<=u;j++)
		{
			f[now][j]=f[!now][j]*2ll%Mod;
			if(j) (f[now][j]+=f[!now][j-1])__;
			if(j<u) (f[now][j]+=f[!now][j+1])__;
		}
	}
	ll re=0;
	for(int i=0;i<=u;i++) (re+=f[now][i])__;
	return re;
}

int main()
{
	scanf("%d%d",&n,&m); n--; m--;
	ll ans1=solve(n);
	ll ans2=n?solve(n-1):0;
	ans1=(ans1-ans2+Mod)%Mod;
	printf("%lld\n",ans1*4ll%Mod);
	
	return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
using namespace std;
int check(int N,long long mask){
	int c=-1;
	long long k=1;
	for(int i=0;i<N;i++,k<<=1){
		if(mask&k){
			if(c>=0)c=-2;
			if(c==-1)c=i;
		}
	}
	return c;
}
int main(){
	for(int N,M,Q;cin>>N>>M>>Q,N;){
		vector<long long>v0(M);
		vector<long long>v1(M);
		string prev(M,'0');
		{
			long long mask=0,k=1;
			for(int i=0;i<N;i++,k<<=1){
				mask|=k;
			}
			for(int i=0;i<M;i++){
				v0[i]=v1[i]=mask;
			}
		}
		for(;Q--;){
			string s,t;
			cin>>s>>t;
			long long mask0=0,mask1=0,k=1;
			for(int i=0;i<s.size();i++,k<<=1){
				if(s[i]=='0')mask0|=k;
				if(s[i]=='1')mask1|=k;
			}
			for(int i=0;i<t.size();i++){
				if((prev[i]^t[i])==0)
					v0[i]&=mask0;
				else
					v1[i]&=mask1;
			}
			prev=t;
		}
		for(int j=0;j<M;j++){
			long long k=1;
			int c0=check(N,v0[j]),c1=check(N,v1[j]),c2=check(N,v1[j]&v0[j]);
			if(c0>=0)putchar(c0<10?c0+'0':c0-10+'A');
			else if(c1>=0)putchar(c1<10?c1+'0':c1-10+'A');
			else if(c2>=0)putchar(c2<10?c2+'0':c2-10+'A');
			else putchar('?');
		}
		puts("");
	}
}

Measured memory_bytes: 1216
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#include <ext/pb_ds/assoc_container.hpp> 
#include <ext/pb_ds/tree_policy.hpp> 
using namespace __gnu_pbds;   
#define ordered_set tree<ll, null_type,less<ll>, rb_tree_tag,tree_order_statistics_node_update> 
#define ld long double
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
const ll M=2002;
std::vector<ll> vtr[M];
ll dist[M][M],ct[M];
int main()
{
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	ll n,x,y;
	cin>>n>>x>>y;
	for(ll i=1;i<n;i++)
	{
		vtr[i].pb(i+1);
		vtr[i+1].pb(i);
	}
	vtr[x].pb(y);
	vtr[y].pb(x);
	memset(dist,-1,sizeof(dist));
	for(ll i=1;i<=n;i++)
	{
		dist[i][i]=0;
		queue<ll> q;
		q.push(i);
		while(!q.empty())
		{
			ll x=q.front();
			q.pop();
			for(auto u:vtr[x])
			{
				if(dist[i][u]==-1)
				{
					dist[i][u]=dist[i][x]+1;
					ct[dist[i][u]]++;
					q.push(u);
				}
			}
		}
	}
	for(ll i=1;i<n;i++)
	{
		cout<<ct[i]/2<<"\n";
	}
	return 0;
}

Measured memory_bytes: 31744
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
    int k,x;
    cin>>k>>x;
    for(int i=x-k+1;i<=(x+k-1);i++){
        cout<<i<<" ";
    }
    cout<<'\n';
    return 0;
}


Measured memory_bytes: 256
#include<bits/stdc++.h>
#pragma GCC optimize ("Ofast")
#pragma GCC optimize("O3")
#define lll __int128_t
#define ll long long int
#define FOR(i,a,b) for(ll (i)=(a);i<(ll)(b);i++)
#define FORr(i,a,b) for(ll(i)=(a);i>(ll)(b);i--)
#define rep(i,n) FOR(i,0,n)
#define rep1(i,n) FOR(i,1,n)
#define outi(a) printf("%lld\n",(a))
#define case(i) cout << "Case " << i << ": ";
#define pb push_back
#define in(n) ll n = read();
#define show(arr) for(auto a : arr) cout << a << " "; cout << endl;
#define inp(arr, n) ll arr[n] ; rep(i,n) arr[i] = read();
#define mp make_pair
#define f first 
#define s second 
#define mod 1000000007
#define modu(a) if(a>=mod) a-=mod;
#define test int tt = read(); rep(i,tt) solve(i+1);
using namespace std;
inline ll read()
{
    ll x=0; static ll p; p=1; static char c; c=getchar();
    while (!isdigit(c)) { if (c=='-') p=-1; c=getchar(); }
    while ( isdigit(c)) { x=(x<<1)+(x<<3)+(c-48); c=getchar(); }
    x*=p;
    return x;
}
int solve(int tt);
int main()
{
    //system("clear");
   // freopen("input.txt", "r", stdin);
   ll ans = 0;
  in(N);
  rep1(i,N+1)
  {
      ll q = log10(i)+1;
      if(q&1) ans++;
  }
  cout << ans <<endl;
}

Measured memory_bytes: 512
#include <iostream>

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

using namespace std;

int n;
int p[25];

int main(void) {
    scanf("%d", &n);
    REP(i, 0, n) scanf("%d", &p[i]);

    int ans = 0;

    REP(i, 1, n - 1) {
    	if ( p[i - 1] < p[i] && p[i] < p[i + 1]) ans++;
    	else if ( p[i] < p[i - 1] && p[i] > p[i + 1] ) ans++;
    }
    
    printf("%d\n", ans);

	return 0;
}


Measured memory_bytes: 256
n, k = map(int, input().split())

# 距離2の頂点対の数の最大値
mx = (n-1)*(n-2)//2

if k > mx:
    print(-1)
    exit()

ans = []
for i in range(1, n):
    ans.append((i, n))

add_edge = mx - k
edge = []
for i in range(1, n-1):
    for j in range(i+1, n):
        edge.append((i, j))

for i in range(add_edge):
    ans.append(edge[i])

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

Measured memory_bytes: 43376
#include<cstdio>
#include <iostream>
#include<algorithm>
#include<string>
#include<queue>
#include<vector>
#include<functional>
#include<cmath>
#include<map>
#include<stack>
#include<set>
#include<numeric>

using namespace std;
typedef long long ll;
typedef pair<int, int>P;

P s[200010];
int main() {
	int W, H;

	cin >> W >> H;
	for (int i = 0; i < W; i++) {
		s[i].second = 0;
		cin >> s[i].first;
	}


	for (int i = 0; i < H; i++) {
		s[i + W].second = 1;
		cin >> s[i + W].first;
	}

	sort(s, s + W + H);
	ll a = W + 1, b = H + 1;
	ll ans = 0;

	for (int i = 0; i < W + H; i++) {
		if (s[i].second == 0) {
			a--;
			ans += s[i].first * b;
		}
		else {
			b--;
			ans += s[i].first*a;
		}
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 1792
#include <bits/stdc++.h>
 
using namespace std;
 
#define MAX 1010
#define MAX_P 12
typedef vector<char> Vec;
typedef vector<Vec> Mat;
 
int dp[MAX][1<<MAX_P];
 
int get_dir(char ch)
{
    if (ch == 'L') return 0;
    if (ch == 'U') return 1;
    if (ch == 'R') return 2;
    return 3;
}
 
int main()
{
    int HPi, HPm;
    while (cin >> HPi >> HPm, HPi) {
        int H, W;
        cin >> H >> W;
        Mat a(H, Vec(W));
        for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
                cin >> a[i][j];
            }
        }
        int T, d, dmg[26] = {}, S;
        char ch;
        cin >> T;        
        for (int i = 0; i < T; i++) {
            cin >> ch >> d;
            dmg[ch-'A'] = d;
        }
        cin >> S;
         
        char dir;
        int dist, x = 0, y = 0;
        vector<int> vec;
        const int dx[] = {-1, 0, 1, 0};
        const int dy[] = {0, -1, 0, 1};
         
        for (int i = 0; i < S; i++) {
            cin >> dir >> dist;
            int d = get_dir(dir);
            for (int j = 0; j < dist; j++) {
                x += dx[d]; y += dy[d];
                vec.push_back(dmg[a[y][x]-'A']);
            }
        }
 
        int P;
        cin >> P;
        vector<int> p(P);
        for (int i = 0; i < P; i++) {
            cin >> p[i];
        }
         
        memset(dp, -1, sizeof(dp));
        dp[0][0] = HPi;
         
        int N = vec.size();
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < (1<<P); j++) {
                if (dp[i][j] <= 0) continue;
                if (dp[i][j] - vec[i] > 0) {
                    dp[i+1][j] = max(dp[i+1][j], dp[i][j] - vec[i]);
                }
                for (int k = 0; k < P; k++) {
                    if (j >> k & 1) continue;
                    dp[i][j|(1<<k)] = max(dp[i][j|(1<<k)], min(dp[i][j] + p[k], HPm));
                }
            }
        }
        bool reachable = 0;
        for (int i = 0; i < (1<<P); i++) {
            if (dp[N][i] > 0) {
                reachable = 1;
                break;
            }
        }
        cout << (reachable ? "YES" : "NO") << endl;
    }
    return 0;
}

Measured memory_bytes: 17400
fn main() {
    b();
}
#[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, bytes) => {
        read_value!($next, String).into_bytes()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn a() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    let nums: Vec<i32> = s.trim().split_whitespace().map(|c| c.parse().ok().unwrap()).collect();
    let ans = if nums[0] == 2 || nums[1] == 2  {
        "No"
    } else {
        "Yes"
    };
    println!("{}",ans);
}

use std::collections::BTreeSet;
fn b() {
    input!{
    n: usize,
    w: [chars; n],
}

let ans = w.iter().collect::<BTreeSet<_>>().len() == n
    && (0..n - 1).all(|i| w[i].last() == w[i + 1].first());

println!("{}", if ans { "Yes" } else { "No" });
}


Measured memory_bytes: 4352
#include<iostream>
using namespace std;
	int main()
	{
  
		int N,M,tmp;
		tmp =  0;
		cin >> N >> M ;
		int a[M];
  
		for (int i ; i < M ;i++){
			cin >> a[i];
			tmp += a[i];
          
		}
		
		 //N 日数　tmp2　必要日数
		if(tmp > N){
          	cout << "-1";
        }else{
			cout << N - tmp;
          
        }
    }
    

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

const int MOD=1000000007;
const int INF=0x3f3f3f3f;
const ll INFL=0x3f3f3f3f3f3f3f3f;

int a[3][3];
bool d[3][3];
int main(){
	rep(i,3)rep(j,3)scanf("%d",&a[i][j]);
	int n;cin>>n;
	rep(i,n){
		int b;scanf("%d",&b);
		rep(j,3)rep(k,3){
			if(a[j][k]==b)d[j][k]=true;
		}
	}
	rep(i,3){
		if(d[i][0]&&d[i][1]&&d[i][2]){
			puts("Yes");return 0;
		}
		if(d[0][i]&&d[1][i]&&d[2][i]){
			puts("Yes");return 0;
		}
	}
	if(d[0][0]&&d[1][1]&&d[2][2]){
		puts("Yes");return 0;
	}
	if(d[0][2]&&d[1][1]&&d[2][0]){
		puts("Yes");return 0;
	}
	puts("No");
}

Measured memory_bytes: 256
object Main extends App {

  import scala.io.StdIn._
  import scala.math._

  solve
  def solve: Unit ={
    val Array(name, namingType) = readLine.trim.split(' ')
    if (namingType == "X") return
    val words = split(name.toList)
    println(
      namingType match {
        case "U" ⇒
          words.indices.foreach(it ⇒ words(it)(0) = words(it)(0).toUpper)
          words.map(_.mkString).mkString
        case "L" ⇒
          words.indices.tail.foreach(it ⇒ words(it)(0) = words(it)(0).toUpper)
          words.map(_.mkString).mkString
        case _ ⇒
          words.map(_.mkString).mkString("_")
      }
    )
    solve
  }
  def split(arg: List[Char], result: List[List[Char]] = Nil::Nil): List[Array[Char]] = {
    arg match {
      case Nil ⇒ result.reverse.map{_.reverse.toArray}
      case '_'::t ⇒ split(t, Nil::result)
      case h::t if h.isUpper ⇒         result match {
        case Nil::r ⇒ split(t, (h.toLower::Nil)::r)
        case _ ⇒ split(t, (h.toLower::Nil)::result)
      }
      case h::t ⇒ split(t, (h::result.head)::result.tail)

    }
  }

  implicit class Extension[T](val value :T){
    def also(func: T ⇒ Unit): T = {
      func(value)
      value
    }
    def let[R](func: T ⇒ R): R = func(value)
  }
}


Measured memory_bytes: 44496
a,b,c = map(int,input().split())
tmp = 0

if a>b:
    tmp = a
    a = b
    b = tmp
    
if b>c:
    tmp = b
    b = c
    c = tmp
    
if a>b:
    tmp = a
    a = b
    b = tmp
    
print(a,b,c)



Measured memory_bytes: 5596
# https://atcoder.jp/contests/tenka1-2017/tasks/tenka1_2017_c
# 式をこねくり回せ

N = int(input())

from itertools import product

for n, h in product(range(1, 3501), range(1, 3501)):
    if (4 / N - 1 / h - 1 / n) <= 0:
        continue
    bunbo = (4 * n * h - N * n - N * h)
    if bunbo == 0:
        continue
    w = (N * h * n) / bunbo
    if w.is_integer():
        print(n, h, int(w))
        exit()


Measured memory_bytes: 3316
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;

const int N = 100500;
vector<int> E[N];
typedef long long llong;

llong A[N];

llong DFS(int x, int p = -1) {
    llong sum = 0;
    llong mx = 0;
    if (p != -1)
        E[x].erase(find(E[x].begin(), E[x].end(), p));
    for (int y : E[x]) {
        llong t = DFS(y, x);
        if (t == -1)
            return -1;
        mx = max(mx, t);
        sum += t;
    }
    if (E[x].empty()) {
        return A[x];
    }
    if (2 * A[x] < sum || sum < A[x] || A[x] < mx) {
        return -1;
    }
    if (p != -1) {
        return 2 * A[x] - sum;
    } else {
        if (E[x].size() == 1) {
            return (A[x] == sum) ? 0 : -1;
        } else {
            return (2 * A[x] == sum) ? 0 : -1;
        }
    }
}

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &A[i]);
    }
    for (int i = 0; i < n - 1; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        --a, --b;
        E[a].push_back(b);
        E[b].push_back(a);
    }
    llong res = DFS(0);
    puts(res == -1 ? "NO" : "YES");
}


Measured memory_bytes: 13184