akhauriyash/Code-Regression huggingface dataset:
//C

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <numeric>
#include <queue>
#include <stack>
#include <map> 
#include <set>
#include <string>
#include <functional>
#include <list>
#include <random>
#include <time.h>
#include <iomanip>
#include <assert.h>
#include <numeric>
#define int long long
//#define ll long long
#define double long double
#define mod 1000000007
#define MAXN (int)1e+5 * 2+1
#define LL_MAX 9223372036854775807	//ない環境用
#define LL_HALFMAX 9223372036854775807 / 2	//ない環境用
#define MIN -(9223372036854775807 / 2)
#define INF 9223372036854775807 / 2
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin(); it!=(c).end(); ++it)
#define ALLOF(c) (c).begin(), (c).end()
#define REPS(i,x) for(int i=1;i<=(int)(x);i++)
#define RREP(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define RREPS(i,x) for(int i=((int)(x));i>0;i--)
#define repl(i,a,b) for(int i=(int)(a);i<(int)(b);i++)
#define mp make_pair


using namespace std;

std::mt19937 mt((int)time(0));

int dx[4] = { 0, 1, 0, -1 }; // x軸方向への変位
int dy[4] = { 1, 0, -1, 0 }; // y軸方向への変位

using Weight = int;
using Flow = int;
struct Edge {
	int src, dst;
	Weight weight;
	Flow cap;
	Edge() : src(0), dst(0), weight(0) {}
	Edge(int s, int d, Weight w) : src(s), dst(d), weight(w) {}
};
using Edges = std::vector<Edge>;
using Graph = std::vector<Edges>;
using Array = std::vector<Weight>;
using Matrix = std::vector<Array>;

void add_edge(Graph &g, int a, int b, Weight w = 1) {
	g[a].emplace_back(a, b, w);
	g[b].emplace_back(b, a, w);
}
void add_arc(Graph &g, int a, int b, Weight w = 1) { g[a].emplace_back(a, b, w); }

struct uf_tree {
	std::vector<int> parent;
	int __size;
	uf_tree(int size_) : parent(size_, -1), __size(size_) {}
	void unite(int x, int y) {
		if ((x = find(x)) != (y = find(y))) {
			if (parent[y] < parent[x]) std::swap(x, y);
			parent[x] += parent[y];
			parent[y] = x;
			__size--;
		}
	}
	bool is_same(int x, int y) { return find(x) == find(y); }
	int find(int x) { return parent[x] < 0 ? x : parent[x] = find(parent[x]); }
	int size(int x) { return -parent[find(x)]; }
	int size() { return __size; }
};



//!!!問題をちゃんと読む!!!
//!!!問題をちゃんと読め!!!
//!!!問題は読みましたか？!!!


signed main() {
	int N, K;
	cin >> N >> K;
	int ma = N - K + 1;
	int mi;
	if (K == 1) {
		mi = ma;
	}
	else {
		mi = 1;
	}


	int ans = 0;
	cout << ma-mi << "\n";

	return 0;
}

Measured memory_bytes: 256
#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll g[4001][4001];
int r,c,k;
ll dp[4001][4001][4];
ll rec(ll i, ll j, ll taken)
{
	if(i>=r)return 0;
	if(j>=c)return 0;
	if(dp[i][j][taken]!=-1)return dp[i][j][taken];
	ll ans=0;

	
	ans=rec(i+1,j,0);
	if(taken<3){
	ans=max(ans,rec(i+1,j,0)+g[i][j]);
	}
	ans=max(ans,rec(i,j+1,taken));
	if(taken<3){
	ans=max(ans,rec(i,j+1,taken+1)+g[i][j]);
	}

	return dp[i][j][taken]=ans;



}
int main()
{
	 cin>>r>>c>>k;
	for(int i=0;i<r;i++)
	{
		for(int j=0;j<c;j++)
		{
			g[i][j]=0;
		}
	}
	for(int i=0;i<k;i++)
	{
		int a,b,v; cin>>a>>b>>v;
		a--; b--;
		g[a][b]=v;
	}
	memset(dp,-1,sizeof(dp));
	cout<<rec(0,0,0);
	
	
}

Measured memory_bytes: 586484
#include<bits/stdc++.h>
using namespace std;
int h,w;
int dx[]={0,0,1,-1};
int dy[]={1,-1,0,0};
char s[1005][1005];
struct node
{
    int x,y,res;
    node(int x=0,int y=0,int res=0):x(x),y(y),res(res){}
};
queue<node>q;
int main()
{
    scanf("%d%d",&h,&w);
    for(int i=1;i<=h;i++)
        scanf("%s",s[i]+1);
    for(int i=1;i<=h;i++)
        for(int j=1;j<=w;j++)
    {
        if(s[i][j]=='#')
            q.push(node(i,j,0));
    }
    int ans=0;
    while(!q.empty())
    {
        node now=q.front();q.pop();
        ans=max(ans,now.res);
        for(int i=0;i<4;i++)
        {
            int xx=dx[i]+now.x;
            int yy=dy[i]+now.y;
            if(xx<1||xx>h||yy<1||yy>w||s[xx][yy]=='#') continue;
            s[xx][yy]='#';
            q.push(node(xx,yy,now.res+1));
        }
    }
    cout<<ans<<endl;
}


Measured memory_bytes: 13328
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve(long long A, long long B)
{
    cout << A * B << endl;
}

// Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
// clang-format off
int main(){
    long long A;
    scanf("%lld",&A);
    long long B;
    scanf("%lld",&B);
    solve(A, B);
    return 0;
}


Measured memory_bytes: 3744
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < n; i++)
#define REPS(i, x) for (int i = 1; i <= (int)(x); i++)
#define REPR(i, n) for (int i = n; i >= 0; i--)
#define FOR(i, m, n) for (int i = m; i < n; i++)
#define FORS(i, m, n) for (int i = m; i <= n; i++)
#define INF 2e9
#define MOD (1000000007)
#define EPS 1e-9
#define ALL(v) v.begin(), v.end()
using namespace std;
typedef long long ll;
typedef long long int lli;
#define MAXN 100001
lli N;
vector<pair<lli, lli>> graph[MAXN];

void dfs(lli cur, lli id, vector<lli> &flg)
{
    flg[cur] = id;
    for (auto p : graph[cur])
    {
        lli point = p.first;
        if (flg[point] == 0)
        {
            int val = (p.second % 2 == 1) ? -1 : 1;
            dfs(point, id * val, flg);
        }
    }
}

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

    REPS(i, N - 1)
    {
        lli x, y, z;
        cin >> x >> y >> z;
        graph[x].emplace_back(y, z);
        graph[y].emplace_back(x, z);
    }

    vector<lli> connectComponent(N + 1, 0);
    lli count = 0;

    REPS(i, N)
    {
        if (connectComponent[i] == 0)
        {
            dfs(i, 1, connectComponent);
            count++;
        }
    }
    REPS(i, N)
    {
        cout << ((connectComponent[i] > 0) ? 1 : 0) << "\n";
    }
}

Measured memory_bytes: 10240
K = int(input())
D = int(input())
MOD = 10**9 + 7

dp = [[[0]*D for _ in range(2)] for _ in range(int(len(str(K)))+1)]
dp[0][0][0] = 1

# 外側の要素から外側のループに置くと参照が速くなる
for digit in range(int(len(str(K)))):
    for smaller_flg in [0,1]:
        lim = 9 if smaller_flg else int(str(K)[digit])
        for digit_num in range(lim+1):
            new_smaller_flg = smaller_flg or digit_num < lim
            for mod_d in range(D):
                new_mod_d = (mod_d + digit_num)%D
                dp[digit+1][new_smaller_flg][new_mod_d] += dp[digit][smaller_flg][mod_d]
                dp[digit+1][new_smaller_flg][new_mod_d] %= MOD

print((dp[int(len(str(K)))][1][0] + dp[int(len(str(K)))][0][0] - 1) % MOD)

Measured memory_bytes: 61788
import java.util.*;
class Main {
  public static void main (String[] args)  {
    
    Scanner sc = new Scanner(System.in);
    
    int a = sc.nextInt();
    int b = sc.nextInt();
    int c = sc.nextInt();
    
    int sum = a+b+c;
    
    int n1=Math.max(Math.max(a,b),c);
    
    sum = sum+n1*9;
    
    System.out.println(sum);

  }
}

Measured memory_bytes: 21716
def main():
    n, k = map(int, input().split())
    h = tuple(map(int, input().split()))
    INF = 10 ** 9
    dp = [INF] * n
    dp[0] = 0
    for i in range(n):
        for j in range(1, k + 1):
            i_j = i + j
            if i_j < n:
                x = dp[i] + abs(h[i] - h[i_j])
                if dp[i_j] > x:
                    dp[i_j] = x
    print(dp[-1])


if __name__ == "__main__":
    main()

Measured memory_bytes: 20724
#include <algorithm>
#include <iostream>
#include <string>
#include <random>
#include <cassert>
#include <cstring>
#include <chrono>
#include <set>
#include <map>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> ii;

int main()
{
  int n;
  cin >> n;
  map<string, int> m;
  for (int i = 0; i < n; ++i) {
    string s;
    cin >> s;
    m[s]++;
  }
  vector<string> v = {"AC", "WA", "TLE", "RE"};
  for (string k : v) {
    cout << k << " x " << m[k] << endl;
  }
  return 0;
}


Measured memory_bytes: 3632
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(int (i) = (s);(i) <= (e);(i)++)
#define all(x) x.begin(),x.end()
struct revran {
  const i64 b, e;
  struct iter {
    i64 i;
    constexpr iter(const i64 i) noexcept: i(i) {}
    void operator++() noexcept { --i; }
    constexpr i64 operator*() const noexcept { return i; }
    constexpr bool operator!=(const iter x) const noexcept { return i != x.i; }
  };
  constexpr revran(const i64 e) noexcept: b(0), e(e) {}
  constexpr revran(const i64 b, const i64 e) noexcept: b(b), e(e) {}
  constexpr iter begin() const noexcept { return iter(e - 1); }
  constexpr iter end() const noexcept { return iter(b - 1); }
};

struct ran {
  const i64 b, e;
  struct iter {
    i64 i;
    constexpr iter(const i64 i) noexcept: i(i) {}
    void operator++() noexcept { ++i; }
    constexpr i64 operator*() const noexcept { return i; }
    constexpr bool operator!=(const iter x) const noexcept { return i != x.i; }
  };
  constexpr ran(const i64 e) noexcept: b(0), e(e) {}
  constexpr ran(const i64 b, const i64 e) noexcept: b(b), e(e) {}
  constexpr iter begin() const noexcept { return iter(b); }
  constexpr iter end() const noexcept { return iter(e); }
  constexpr revran rev() const noexcept { return revran(b, e); }
};

constexpr ran rin(const i64 e) noexcept { return ran(1, e + 1); }
constexpr ran rin(const i64 b, const i64 e) noexcept { return ran(b, e + 1); }

int main() {
  i64 N;
  cin >> N;
  vector<i64> d(N);
  for(int i: ran(N)) cin >> d[i];
  sort(all(d));
  i64 left = d[N / 2 - 1];
  i64 right = d[N / 2];
  cout << right - left << endl;
}


Measured memory_bytes: 1024
io = STDIN
n=io.gets.to_i
s=io.gets.chomp.split(//).chunk_while{|a,b|a==b}.to_a
size=s.size
def cnt_ar(ss,ch)
  ss.select{|ar|ar[0]==ch}.map{|ar|ar.size}
end
white=cnt_ar(s,".") #今の色の数
all_black_cnt=white.inject(0){|s,i|s+i}  #all blackにするために動かした数
ans=move=all_black_cnt
s.each do |ar|
  if ar[0]=="#"
    move+=ar.size
  else
    move-=ar.size
  end
  ans=[ans,move].min
end
puts ans

Measured memory_bytes: 46332
N,M=map(int,input().split())
H=list(map(int,input().split()))
ls=[list(map(int,input().split())) for _ in range(M)]#1から
C=[0 for _ in range(N)]
for i in range(M):#O(M)でいけるはず
  if H[ls[i][0]-1]>H[ls[i][1]-1]:
    C[ls[i][1]-1]=-1
  elif H[ls[i][0]-1]<H[ls[i][1]-1]:
    C[ls[i][0]-1]=-1
  elif H[ls[i][0]-1]==H[ls[i][1]-1]:
    C[ls[i][0]-1]=-1
    C[ls[i][1]-1]=-1
print(C.count(0))

Measured memory_bytes: 32020
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cstring>
#include <set>
#include <map>
#include <queue>
#include <stack>
#define rep(i, s, g) for ((i) = (s); (i) < (g); ++(i))
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
const ll MOD = 1e9 + 7;
const ll INF = (1e18) + 1;

int main(void)
{
    int n;
    string s;
    int i;

    cin >> n >> s;

    rep(i, 0, s.size())
    {
        cout << (char)((s[i] - 'A' + n) % 26 + 'A');
    }

    cout << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <utility>
#include <string>
#include <vector>
#include <set>
#include <stack>
#include <queue>
#include <map>
#include <math.h>
#include <string.h>
#include <iomanip>
#include <numeric>
#include <cstdlib>
#include <cstdint>
#include <cmath>
#include <functional>
#include <limits>
#include <cassert>
#include <bitset>

using namespace std;

/* template */

using ll = long long;

void debug_out() { std::cout << std::endl; }
 
template <typename Head, typename... Tail>
void debug_out(Head H, Tail... T) {
  cout << H << " ";
  debug_out(T...);
}

#ifdef LOCAL
#define debug(...) cout << "debug: "; debug_out(__VA_ARGS__)
#else
#define debug(...) 
#endif

#define rep(i, a, n) for (int i = (int)(a); i < (int)(n); i++)
#define rrep(i, a, n) for (int i = ((int)(n-1)); i >= (int)(a); i--)
#define Rep(i, a, n) for (long long i = (long long)(a); i< (long long)(n); i++)
#define RRep(i, a, n) for (long long i = ((long long)(n-1ll)); i>=(long long)(a); i--)
#define all(v) (v).begin(),(v).end()
#define rall(v) (v).rbegin(),(v).rend()

template <typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T> vec) {
  for (std::size_t i = 0; i < vec.size(); i++)os << vec[i] << (i + 1 == vec.size() ? "" : " ");
  return os;
}

struct Edge{
    int to;
    ll weight;
    Edge(int t, ll w) : to(t), weight(w){ }
};

struct edge{
    int from;
    int to;
    ll weight;
    edge(int f,int t,ll w) : from(f), to(t), weight(w){ }
};


using Graph = vector<vector<Edge>>;
using graph = vector<vector<int>>;
using edges = vector<edge>;

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

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

template <class T>
T lcm(T a, T b){
    return (a*b)/gcd(a,b);
}

constexpr ll LNF = 1LL<<50;

constexpr int INF = 1e9+7;

const double PI=3.14159265358979323846;


vector<int> dx = {-1,0,1,0,-1,1,-1,1};
vector<int> dy = {0,-1,0,1,1,-1,-1,1};

/* template */

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    ll n; cin >> n;
    vector<ll> a(n+1);
    rep(i,0,n+1) cin >> a[i];
    vector<ll> p = a;
    rrep(i,0,n){
        p[i] += p[i+1];
    }
    ll c = 1;
    ll ans = 0;
    rep(i,0,n+1){
        if(c<a[i]){
            cout << -1 << endl;
            return 0;
        }
        ans += c;
        c -= a[i];
        c *= 2;
        chmin(c,p[i+1]);
    }
    cout << ans << endl;
}


Measured memory_bytes: 4764
n=int(input())
a,b,c,d=0,0,0,0
for i in range(n):
    s=input()
    if len(s)>1:
        for j in range(1,len(s)):
            if s[j-1]+s[j]=="AB":
                d+=1
    if s[0]=="B"and s[-1]=="A":
        b+=1
    elif s[-1]=="A":
        a+=1
    elif s[0]=="B":
        c+=1
if a+c!=0:
    print(d+b+min(a,c))
else:
    print(d+max(0,b-1))

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

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


Measured memory_bytes: 256
import numpy as np
import itertools
n,m,x = map(int, input().split())
ca = np.zeros((n,m+1))
for i in range(n):
    ca[i] = [int(i) for i in input().split()]

'''
N行を読む or 読まないで全探索する
itertools.productでTrue,Falseの全組み合わせリストを生成し、
Numpyのブールインデックス参照で本を選択する
答えは整数型じゃないといけない・・・
'''

p = itertools.product([True,False], repeat = n)
ans_l = []
for i in p:
    ca_cut = ca[i,:]
    if len(ca_cut) == 0: 
        continue
    ca_cut_sum = ca_cut.sum(axis=0)
    if all(ca_cut_sum[1:] >= x):
        ans_l.append(ca_cut_sum[0])
if len(ans_l) == 0:
    ans = -1
else:
    ans = min(ans_l)
print(int(ans))

Measured memory_bytes: 27280
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <ctime>
#define INF 999999999
#define mod 1000000007
 
#define rep(i,n) for(int i=0;i<int(n);i++)
#define rrep(i,n) for(int i=(n);i>=0;i--)
#define REP(i,a,b) for(int i=(a);i<int(b);i++)
#define all(x) (x).begin(),x.end()
#define pb push_back
#define mp make_pair
#define MOD(x) (x%(mod))
using namespace std;
 
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pi;
 
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
bool debug=false;
/*---------------------------------------------------*/
 
int n,m;
ll ans;
int wide[1500001],hight[1500001];
int w[1505],h[1505];
 
void enumerate_hight(){
  int sum;
  for(int i=0;i<n;i++){
    sum=0;
    for(int j=i;j<n;j++){
      sum+=h[j];
      hight[sum]++;
    }
    h[i]=0;
  }
}

void enumerate_wide(){
  int sum;
  for(int i=0;i<m;i++){
    sum=0;
    for(int j=i;j<m;j++){
      sum+=w[j];
      wide[sum]++;
    }
    w[i]=0;
  }
}

void solve(){
  ll max_w=0,max_h=0,mini;
  ans=0;
  for(int i=0;i<n;i++){scanf("%d",&h[i]);max_h+=h[i];}
  for(int i=0;i<m;i++){scanf("%d",&w[i]);max_w+=w[i];}
  mini=min(max_w,max_h);
  rep(i,mini+1)wide[i]=hight[i]=0;
  enumerate_hight();
  enumerate_wide();
  rep(i,mini+1){ans+=wide[i]*hight[i];}
  cout<<ans<<endl;
}
 
int main(){
  while(scanf("%d%d",&n,&m)){
    if(n==0&&m==0)break;
    solve();
  }
}

Measured memory_bytes: 7120
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;
#define INF (1<<30)
#define INFLL (1ll<<60)
typedef pair<int, int> P;
typedef pair<int, P> E;
#define MOD (1000000007ll)
#define l_ength size

void mul_mod(ll& a, ll b){
	a *= b;
	a %= MOD;
}

void add_mod(ll& a, ll b){
	b += MOD;
	a += b;
	a %= MOD;
}

int c[255816],l[225816];
ll dp[225816];

int main(void){
	int n,i;
	cin >> n;
	for(i=0; i<n; ++i){
		cin >> c[i];
		--c[i];
	}
	dp[0] = 1;
	for(i=0; i<n; ++i){
		add_mod(dp[i+1],dp[i]);
		if(l[c[i]] && i>l[c[i]]){
			add_mod(dp[i+1],dp[l[c[i]]]);
		}
		l[c[i]] = i+1;
	}
	cout << dp[n] << endl;
	return 0;
}


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

using namespace std;

#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define all(x) (x).begin (),(x).end()
#define sqrt(x) sqrt(abs(x))
#define re return
#define sz(x) ((int)(x).size ())
#define prev PREV
#define next NEXT

using ll = long long;
using ii = pair<int, int>;
using ld = long double;
using D = double;
using vi = vector<int>;
using vii = vector<ii>;
using vvi = vector<vi>;
using vs = vector<string>;

template<typename T> T abs (T x) { re x < 0 ? -x : x; }
template<typename T> T sgn (T x) { re x < 0 ? -1 : (x > 0 ? 1 : 0); }
template<typename T> T sqr (T x) { re x * x; }
template<typename T> T gcd (T a, T b) { re a ? gcd (b % a, a) : b; }

int n;
int m;

int main () {
	cin >> n >> m;
	if (n % m == 0) {
		cout << -1 << endl;
		re 0;
	}
	for (int i = 2; ; i++)
		if (((ll)n * i) % m != 0) {
			cout << (ll)n * i << endl;
			re 0;
		}
	return 0;
}

Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cfloat>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <memory>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

// c++11
#include <array>
#include <tuple>
#include <unordered_map>
#include <unordered_set>

#define mp make_pair
#define mt make_tuple
#define rep(i, n) for (int i = 0; i < (n); i++)

using namespace std;

using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;

const ll INF = 1LL << 50;
const double EPS = 1e-9;
const ll MOD = 1000000007;

const int dx[] = {1, 0, -1, 0}, dy[] = {0, -1, 0, 1};
const int MAX_N = 105;
ll N,W;
vector<pair<ll,ll>> items;
ll base_weight;
ll dp[MAX_N][MAX_N][4 * MAX_N];

ll memo(int pos, int cnt, int remain){
  if (base_weight *(ll)cnt + remain > W){
    return -INF;
  }
  if (pos >= N){
    return 0;
  }
  ll &res = dp[pos][cnt][remain];
  if (res >= 0){
    return res;
  }
  res = -INF;
  ll point = items[pos].first - base_weight;
  ll value = items[pos].second;
  res = max(res, memo(pos + 1, cnt, remain));
  res = max(res, memo(pos + 1, cnt + 1, remain + point) + value);
  return res;
}

int main() {
  cin >> N >> W;
  items.resize(N);
  for (auto &val : items){
    cin >> val.first >> val.second;
  }
  base_weight = items[0].first;
  memset(dp, -1, sizeof(dp));
  ll res = max(0LL, memo(0, 0, 0));
  cout << res << endl;
  return 0;
}


Measured memory_bytes: 36480
import java.util.*;
import java.util.Map.Entry;

import javax.swing.text.Segment;
import javax.xml.ws.WebEndpoint;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;

import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
 
public class Main //implements Runnable
{
//    static int dx[]={-1,0,1,0};
//    static int dy[]={0,-1,0,1};
	
    public static void main(String[] args)   throws Exception, IOException{        
        long mod=1000000007;
        Reader sc = new Reader(System.in);
        PrintWriter out=new PrintWriter(System.out);

        int n=sc.nextInt();
        int a[]=sc.nextIntArray(n);
        int c=0;
        for (int i = 0; i < a.length; i++) {
			if(c+1==a[i])c++;
		}
        if(c==0)ret("-1");

        out.println(n-c);
     	out.flush();
    }


    static void ret(String ans) {
    	System.out.println(ans);
    	System.exit(0);
    }
    
    static boolean validpos(int x,int y,int r, int c){
        return x<r && 0<=x && y<c && 0<=y;
    }

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

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

//class P implements Comparable<P>{
//    int a,b;
//    P(int a, int b) {
//    	this.b=b;
//    	this.a=a;
//    }
//
//    public int compareTo(P p){
//        return -p.a+a;//as
//    }
//}

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


Measured memory_bytes: 47572
'use strict'

function main(s) {

  s = s.split('\n');

  const k = Number(s[1]);
  const xs = s[2].split(' ').map(n => Number(n));

  let sum = 0;

  for (const x of xs) {
    sum += Math.min(2 * x, 2 * (k - x));
  }

  console.log(sum);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


Measured memory_bytes: 7372
// Problem : C - H and V
// Contest : AtCoder - AtCoder Beginner Contest 173
// URL : https://atcoder.jp/contests/abc173/tasks/abc173_c
// Memory Limit : 1024 MB
// Time Limit : 1000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <ext/pb_ds/tree_policy.hpp> // Including tree_order_statistics_node_update

using namespace std;
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
ordered_set;	

#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(int i = (a); i >= (b); --i)
#define RI(i,n) FOR(i,1,(n))
#define REP(i,n) FOR(i,0,(n)-1)
#define mini(a,b) a=min(a,b)
#define maxi(a,b) a=max(a,b)
#define pb push_back
#define st first
#define nd second
#define sz(w) (int) w.size()
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<pii, int> para;
const ll inf = 1e18 + 7;
const ll maxN = 1e6 + 5;
const ll MOD = 1e9 + 7;

string s[maxN];
string s2[maxN];
int n, m, k;

bool solve(int mask) {
	int ile = 0;
	REP(i, n) {
		s2[i] = s[i];
	}
	REP(i, n) {
		if (mask & (1 << i)) {
			REP(j, m) {
				s2[i][j] = '.';
			}
		}
	}
	FOR(i, n, n + m - 1) {
		if (mask & (1 << i)) {
			int j = i - n;
			REP(k, n) {
				s2[k][j] = '.';
			}
		}
	}
	REP(i, n) {
		REP(j, m) {
			if (s2[i][j] == '#') ile++;
		}
	}
	return ile == k;
}

// sprawdz MODULO!
int main() {
    mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> n >> m >> k;
	REP(i, n) {
		cin >> s[i];
	}
	int ans = 0;
	REP(i, (1 << (n + m))) {
		if (solve(i)) ans++;
	}
	cout << ans;
	return 0;
}
 


Measured memory_bytes: 66112
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define P pair<ll,ll>
#define FOR(I,A,B) for(ll I = (A); I < (B); ++I)
#define POSL(x,v) (lower_bound(x.begin(),x.end(),v)-x.begin()) //ai>=v  x is sorted
#define POSU(x,v) (upper_bound(x.begin(),x.end(),v)-x.begin()) //ai>v  x is sorted
#define NUM(x,v) (POSU(x,v)-POSL(x,v))  //x is sorted
#define SORT(x) (sort(x.begin(),x.end())) // 0 2 2 3 4 5 8 9
#define REV(x) (reverse(x.begin(),x.end())) //reverse
#define TO(x,t,f) ((x)?(t):(f))
#define CLR(mat) memset(mat, 0, sizeof(mat))
#define FILV(x,a) fill(x.begin(),x.end(),a)
#define FILA(ar,N,a) fill(ar,ar+N,a)
#define NEXTP(x) next_permutation(x.begin(),x.end())
ll gcd(ll a,ll b){if(a<b)swap(a,b);if(a%b==0)return b;else return gcd(b,a%b);}
ll lcm(ll a,ll b){ll c=gcd(a,b);return ((a/c)*(b/c)*c);}//saisyo kobaisu
#define pb push_back
#define pri(aa) cout<<(aa)<<endl
#define mp(x,y) make_pair(x,y)
#define fi first
#define se second
const ll INF=1e9+7;
const ll N = 300003;

class UnionFind{
public:
	vector<int> par;
	//0-indexed
	void init(int n = 1) {
		par.resize(n);
		for (int i = 0; i < n; ++i) par[i] = i;
	}
	int root(int x = 1){
		if(par[x]==x)return x;
		else{
			return par[x] = root(par[x]);
		}
	}
	void unite(int x = 1,int y = 1){
		x = root(x);
		y = root(y);
		if(x==y)return;
		else par[x] = y;
	}
};
class dijkstra{ 
//0indexed 
public: 
	int v,startv; 
	vector<int> d; 
	vector<vector<pair<int,int> > >e; 

	void initsize(int n0){ 
		d.resize(n0); 
		for(int i=0;i<n0;i++)d[i]=INT_MAX; 
		vector<pair<int,int> > ep; 
		for(int i=0;i<n0;i++)e.push_back(ep); 
		v=n0; 
	} 

	void initstart(int s){ 
		startv=s;
		d[s]=0;
	}

	void make_edge(int x,int y,int cost){ 
		e[x].push_back(make_pair(y,cost)); 
		e[y].push_back(make_pair(x,cost)); 
	}

	void make_edgedir(int x,int y,int cost){ 
		e[x].push_back(make_pair(y,cost)); 
	}

	void calcdistance(){ 
		// <-cost,x> 
		//cost startv->x 
		priority_queue<pair<int,int> > q; 
		pair<int,int> p; 
		vector<bool> did; 
		for(int i=0;i<v;i++)did.push_back(false); 
		did[startv]=true; 
		for(int i=0;i<e[startv].size();i++){ 
			p.first=-e[startv][i].second; 
			p.second=e[startv][i].first; 
			q.push(p); 
		}
		while(q.size()!=0){
			pair<int,int> p;
			p=q.top();
			q.pop();
			int x,costsx;
			x=p.second;
			costsx=-p.first;
			if(did[x]==true)continue;
			did[x]=true;
			d[x]=costsx;
			for(int i=0;i<e[x].size();i++){
				p.first=-(d[x]+e[x][i].second);
				p.second=e[x][i].first;
				if(did[p.second]==false)q.push(p);
			}
		}
	}
};
int k;

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cin>>k;
	UnionFind uf;
	uf.init(k);
	dijkstra di;
	di.initsize(k);
	FOR(i,1,k){
		uf.unite(i,(i*10)%k);
	}
	di.initstart(uf.root(1));
	FOR(i,1,k){
		int x = uf.root(i);
		int y = uf.root((i+1)%k);
		if(x!=y)di.make_edgedir(x,y,1);
	}
	di.calcdistance();
	int g = uf.root(0);
	cout<<di.d[g]+1<<endl;
	return 0;
}


Measured memory_bytes: 5748
#include<stdio.h>

int main(void){
	int kou[4][3][10];
	int n,b,f,r,v,i,j,k;
for(i=0;i<4;i++)for(j=0;j<3;j++)for(k=0;k<10;k++)kou[i][j][k]=0;
scanf("%d",&n);
for(i=0;i<n;i++){
   scanf("%d %d %d %d",&b,&f,&r,&v);
   kou[b-1][f-1][r-1]+=v;
}
for(i=0;i<4;i++){
	for(j=0;j<3;j++){
		for(k=0;k<10;k++){
			printf(" %d",kou[i][j][k]);
		}
		printf("\n");
	}
	if(i<3)	printf("####################\n");
}
	return 0;
}

Measured memory_bytes: 612
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mod 998244353
#define h1 7897897897897897
#define h2 7897466719774591
#define b1 98762051
#define b2 98765431
#define inf 1000000000
#define pi 3.1415926535897932384626
#define LMAX 9223372036854775807
#define ll long long
#define fi first
#define se second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define vp vector<pii>
#define SET(a, b) memset(a, b, sizeof(a));
#define all(x) (x).begin(), (x).end()
#define flush fflush(stdout)
#define debug printf("Hello\n")
#define FOR(i, a, b) for (int i = (a); i <= (b); i++)
#define FORD(i, a, b) for (int i = (a); i >= (b); i--)
int n, m, k, x, y, sum, cnt, a[100005], f[100005];
ll ans = 1;
int main () {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  FOR(i, 1, n) {
    cin >> a[i];
    f[a[i]]++;
    m = max(m, a[i]);
  }
  if (a[1] != 0) {
    cout << 0 << endl;
    return 0;
  }
  FOR(i, 2, n) {
    if (a[i] == 0) {
      cout << 0 << endl;
      return 0;
    }
  }
  FOR(i, 2, m) {
    FOR(j, 1, f[i]) {
      ans = (1LL* ans * (f[i-1])) % mod;
    }
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 1024
/* ****mittal**** */
#include<bits/stdc++.h>
#define ll          long long int 
#define pb          push_back
#define endl        '\n'
#define pii         pair<ll int,ll int>
#define vi          vector<ll int>
#define all(a)      (a).begin(),(a).end()
#define F           first
#define S           second
#define sz(x)       (ll int)x.size()
#define hell        1000000007
#define rep(i,a,b)    for(ll int i=a;i<b;i++)
#define repr(i,a,b)   for(ll int i=a;i>=b;i--)
#define lbnd    lower_bound
#define ubnd        upper_bound
#define mp          make_pair
using namespace std;

#define N  100005
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int TESTS=1;
//    cin>>TESTS;
    while(TESTS--)
    {
        ll n,k;
        map<char,ll>lol;
        cin>>n>>k;
        ll a[5];
        cin>>a[0]>>a[1]>>a[2];
        lol['r']=0;
        lol['s']=1;
        lol['p']=2;
        string s;
        cin>>s;
        ll ans=0;
        for(int i=1;i<=k;i++)
        {   ll p=lol[s[i-1]];
        	p=(p+2)%3;
        	//cout<<p;
        	ll x=p;
        	ll cnt=1;
        	for(int j=i+k;j<=n;j+=k)
        	{
               ll o=(lol[s[j-1]]+2)%3;
               if(x==o)
               	cnt++;
               else
               {
               	ans+=ceil(cnt/2.00)*a[x];
               	  x=o;
               	  cnt=1;

               }
            //   cout<<ans<<endl;
        	}
        	ans+=ceil(cnt/2.00)*a[x];
        	//cout<<ans<<endl;
        }
        cout<<ans;

    }
    return 0;
}

Measured memory_bytes: 512
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<utility>
#define upd(x,y) (x+=y,(x>=mod?x-=mod:0))
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define ok(i,j) (xz[i][j].fir<=xz[i][j].sec)
#define gc getchar()
#define mp make_pair
#define fir first
#define sec second
#define debug(x) cerr<<#x<<"="<<x
#define sp <<" "
#define ln <<endl
#define mod 1000000007
#define N 310
using namespace std;
typedef pair<int,int> pii;
inline int inn()
{
	int x,ch;while((ch=gc)<'0'||ch>'9');
	x=ch^'0';while((ch=gc)>='0'&&ch<='9')
		x=(x<<1)+(x<<3)+(ch^'0');return x;
}
pii xz[N][5];int dp[2][N][N];
int main()
{
	int n=inn(),m=inn(),ans=0;
	rep(i,0,n) rep(j,1,3) xz[i][j]=mp(i+1,-1);
	for(int l,r,x;m;m--)
		l=inn(),r=inn(),x=inn(),
		xz[r][x].fir=min(xz[r][x].fir,l),
		xz[r][x].sec=max(xz[r][x].sec,l);
	rep(i,0,n) rep(j,1,2)
		if(xz[i][j].fir<=xz[i][j+1].sec) return !printf("0\n");
	int now=0,nxt=1;dp[now][0][0]=1;
	for(int i=0,v;i<=n;i++,swap(now,nxt))
	{
		rep(j,0,i+1) memset(dp[nxt][j],0,sizeof(int)*(j+1));
		rep(j,0,i) rep(k,0,j)
		{
			if(!(v=dp[now][j][k])) continue;
			if(ok(i,1)&&j>=xz[i][1].fir) { dp[now][j][k]=0;continue; }
			if(ok(i,2)&&(j<xz[i][2].sec||k>=xz[i][2].fir)) { dp[now][j][k]=0;continue; }
			if(ok(i,3)&&k<xz[i][3].sec) { dp[now][j][k]=0;continue; }
			upd(dp[nxt][j][k],v),upd(dp[nxt][i][k],v),upd(dp[nxt][i][j],v);
		}
	}
	rep(i,0,n) rep(j,0,i) if(dp[nxt][i][j]) upd(ans,dp[nxt][i][j]);
	return !printf("%d\n",ans);
}

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

class P
{
    static void Main()
    {
        int[] wab = Console.ReadLine().Split().Select(int.Parse).ToArray();
        Console.WriteLine(Math.Max(Math.Abs(wab[2] - wab[1]) - wab[0],0));
    }
}

Measured memory_bytes: 13268
import java.util.Scanner;

public class Main {
	public static void main(String[] args){
		 Scanner sc = new Scanner(System.in);
		 long X=sc.nextLong();
	     sc.close();
	     
	     long[] num=new long[121];
	     for(int i=0;i<121;i++)
	    	 num[i]=(long)Math.pow(i, 5);
	     
	     for(int i=0;i<num.length;i++) {
	    	 for(int j=0;j<num.length;j++) {
	    		 if(num[i]-num[j]==X) {
	    			 System.out.println(i+" "+j);
	    			 System.exit(0);
	    		 }else if(num[i]+num[j]==X) {
	    			 System.out.println(i+" -"+j);
	    			 System.exit(0);
	    		 }
	    	 }
	     }
	 }
}


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

#ifndef ONLINE_JUDGE 
const bool DEBUG = true;
#else
const bool DEBUG = false;
#endif

using ll = long long;
using ull = unsigned long long;

#define F first
#define S second
#define all(x) begin(x), end(x)

template <class T>
void read_vector(vector<T>& arr) {
	const int size = arr.size();
	for (int i = 0; i < size; ++i) cin >> arr[i];
}

//template <class T>
//vector<T> create_vector(int n) {
//	vector<T> v(n);
//	for (int i = 0; i < size; ++i) cin >> v[i];
//	return v;
//}





void exec()
{
	string a, b;
	cin >> a >> b;

	string ans = "";
	vector<vector<int>> dp(b.length() + 1, vector<int>(a.length() + 1, 0));
	const int A = a.length(), B = b.length();

	for (int i = 1; i <= B; ++i) {
		for (int j = 1; j <= A; ++j) {
			if (b[i - 1] == a[j - 1])
				dp[i][j] = dp[i - 1][j - 1] + 1;
			else
				dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
		}
	}

	/*for (int i = 0; i <= B; ++i) {
		for (int j = 0; j <= A; ++j)
			cout << dp[i][j] << " ";
		cout << endl;
	}*/

	int i = B, j = A;
	while (i > 0 && j > 0 && dp[i][j] > 0) {
		int p = dp[i][j];
		while (j > 0 && dp[i][j - 1] == dp[i][j]) --j;
		while (i > 0 && dp[i - 1][j] == dp[i][j]) --i;

		ans += b[i - 1];
		--j; --i;
	}
	reverse(all(ans));

	cout << ans << endl;
}

















int main()
{
	exec();

	return 0;
}

Measured memory_bytes: 35584
N = int(input())
S = input()

f = ""
b = ""

L = [0] * N
con = 0

for i in range(N - 1):
  b = S[i + 1:]
  if S[i] in b and S[i] not in f:
    con += 1
    L[i] = con
  elif S[i] not in b and S[i] in f:
    con -= 1
    L[i] = con
  f += S[i]

  
print(max(L))

Measured memory_bytes: 3064
/***************************************************************
	File name: ARC093F.cpp
	Author: ljfcnyali
	Create time: 2020年07月25日 星期六 11时47分22秒
***************************************************************/
#include<bits/stdc++.h>

using namespace std;

#define REP(i, a, b) for ( int i = (a), _end_ = (b); i <= _end_; ++ i ) 
#define mem(a) memset ( (a), 0, sizeof ( a ) ) 
#define str(a) strlen ( a ) 
#define pii pair<int, int>
#define int long long
typedef long long LL;

const int maxn = 1 << 16;
const int Mod = 1e9 + 7;

int n, m, a[maxn], f[17][maxn], fac[maxn], inv[maxn];

inline int power(int a, int b) { int r = 1; while ( b ) { if ( b & 1 ) r = r * a % Mod; a = a * a % Mod; b >>= 1; } return r; }

inline int C(int n, int m) { return n < m ? 0 : (fac[n] * inv[m] % Mod) * inv[n - m] % Mod; }

inline int sgn(int n) { return n & 1 ? -1 : 1; }

signed main()
{
    n = maxn - 1; fac[0] = inv[0] = 1; REP(i, 1, n) fac[i] = fac[i - 1] * i % Mod;
    inv[n] = power(fac[n], Mod - 2); for ( int i = n - 1; i >= 1; -- i ) inv[i] = inv[i + 1] * (i + 1) % Mod;
    scanf("%lld%lld", &n, &m);
    REP(i, 1, m) scanf("%lld", &a[i]);
    reverse(a + 1, a + m + 1);
    f[0][0] = 1;
    REP(i, 1, m) REP(j, 0, (1 << n) - 1) 
    {
        f[i][j] = (f[i][j] + f[i - 1][j]) % Mod;
        int sum = 0; 
        REP(k, 1, n) if ( (j >> k - 1) & 1 ) sum += 1 << k - 1;
        REP(k, 1, n)
        {
            if ( (j >> k - 1) & 1 ) continue ;
            int s = j | (1 << k - 1);
            int num = (1 << n) - a[i];
            if ( num >= sum ) f[i][s] = (f[i][s] + (f[i - 1][j] * C(num - sum, (1 << k - 1) - 1) % Mod) * fac[1 << k - 1]) % Mod;
        }
    }
    int ans = 0;
    REP(j, 0, (1 << n) - 1)
    {
        int num = 0, sum = 0; 
        REP(i, 1, n) if ( (j >> i - 1) & 1 ) { ++ sum; num += 1 << i - 1; }
        ans = (ans + sgn(sum) * fac[(1 << n) - 1 - num] * f[m][j]) % Mod;
    }
    ans = ans * (1 << n) % Mod;
    printf("%lld\n", (ans + Mod) % Mod);
    return 0;
}


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

int main() {

  string s;
  int len1, len2, len3;
  bool flg = true;
  cin >> s;
  len1 = s.size();
  len2 = (len1-1)/2;

  for (int i = 0; i < len1; i++) {
    if (s.at(i) != s.at(len1-(i+1))) {
      flg = false;
    }
  }
  
  for (int i = 0; i < len2; i++) {
    if (s.at(i) != s.at(len2-(i+1))) {
      flg = false;
    }
  }
  
  for (int i = len2+1, j = 0; i < len1; i++, j++) {
    if (s.at(i) != s.at(len1-(j+1))) {
      flg = false;
    }
  }

  if (flg == true) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }

}


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

int main() {
  int64_t n, k;
  cin >> n >> k;
  vector<int64_t> a(n), dp_under(41, -1e18), dp_exact(41);
  for (int i = 0; i < n; i++) {
    cin >> a.at(i);
  }
  for (int i = 39; i >= 0; i--) {
    int64_t s[2] = {0, 0};
    for (int j = 0; j < n; j++) {
      s[(a.at(j) >> i) & 1]++;
    }
    swap(s[0], s[1]);
    s[0] <<= i;
    s[1] <<= i;
    dp_under.at(i) = dp_under.at(i + 1) + max(s[0], s[1]);
    dp_exact.at(i) = dp_exact.at(i + 1) + s[(k >> i) & 1];
    if (((k >> i) & 1) == 1) {
      dp_under.at(i) = max(dp_under.at(i), dp_exact.at(i + 1) + s[0]);
    }
  }
  cout << max(dp_under.at(0), dp_exact.at(0)) << endl;
}


Measured memory_bytes: 1024
#include <bits/stdc++.h>
#define ADD(a, b) a = (a + ll(b)) % mod
#define MUL(a, b) a = (a * ll(b)) % mod
#define MAX(a, b) a = max(a, b)
#define MIN(a, b) a = min(a, b)
#define rep(i, a, b) for(int i = int(a); i < int(b); i++)
#define rer(i, a, b) for(int i = int(a) - 1; i >= int(b); i--)
#define all(a) (a).begin(), (a).end()
#define sz(v) (int)(v).size()
#define pb push_back
#define sec second
#define fst first
#define debug(fmt, ...) Debug(__LINE__, ":", fmt, ##__VA_ARGS__)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef pair<int, pi> ppi;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vl> mat;
typedef complex<double> comp;
void Debug() {cerr << '\n'; }
template<class FIRST, class... REST>void Debug(FIRST arg, REST... rest){
	cerr<<arg<<" ";Debug(rest...);}
template<class T>ostream& operator<<(ostream& out,const vector<T>& v) {
	out<<"[";if(!v.empty()){rep(i,0,sz(v)-1)out<<v[i]<<", ";out<<v.back();}out<<"]";return out;}
template<class S, class T>ostream& operator<<(ostream& out,const pair<S, T>& v){
	out<<"("<<v.first<<", "<<v.second<<")";return out;}
const int MAX_N = 500010;
const int MAX_V = 100010;
const double eps = 1e-6;
const ll mod = 1000000007;
const int inf = (1 << 30) - 1;
const ll linf = 1LL << 60;
const double PI = 3.14159265358979323846;
mt19937 rng; //use it by rng() % mod, shuffle(all(vec), rng)
///////////////////////////////////////////////////////////////////////////////////////////////////

int N, M;
ll A[MAX_N];
pl P[MAX_N];

void solve() {
	cin >> N >> M;
	rep(i, 0, N) cin >> A[i];
	sort(A, A + N);
	rep(i, 0, M) cin >> P[i].sec >> P[i].fst;
	sort(P, P + M);
	int at = N - 1;
	int bat = M - 1;
	ll sum = 0;
	int sz = 0;
	while(sz < N) {
		if(bat < 0 || A[at] >= P[bat].fst) {
			sum += A[at]; sz++;
			at--;
		}
		else {
			sum += P[bat].fst; sz++;
			P[bat].sec--;
			if(!P[bat].sec) bat--;
		}
	}
	cout << sum << "\n";
}

uint32_t rd() {
	uint32_t res;
#ifdef __MINGW32__
	asm volatile("rdrand %0" :"=a"(res) ::"cc");
#else
	res = std::random_device()();
#endif
	return res;
}

int main() {
#ifndef LOCAL
	ios::sync_with_stdio(false);
    cin.tie(0);
#endif
    cout << fixed;
	cout.precision(20);
    cerr << fixed;
	cerr.precision(6);
	rng.seed(rd());
#ifdef LOCAL
	//freopen("in.txt", "wt", stdout); //for tester
	if(!freopen("in.txt", "rt", stdin)) return 1;
#endif	
	solve();
    cerr << "Time: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
	return 0;
}



Measured memory_bytes: 5888
n,m,l = list(map(int,input().split()))

A = []
B = []

for i in range(n):
    A.append(list(map(int,input().split())))

for i in range(m):
    B.append(list(map(int,input().split())))

C = [[0 for i in range(l)] for j in range(n)]

#print(A)
#print(B)
#print(C)

for i in range(n):
    for j in range(l):
       for k in range(m):
            #print(f"i:{i},j:{j},k:{k}")
            C[i][j] += A[i][k] * B[k][j]

for i in C:
    print(*i)


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

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

# define REP(i,n) for (int i=0;i<(n);++i)
# define rep(i,a,b) for(int i=a;i<(b);++i)
# define p(s) std::cout << s ;
# define pl(s)  std::cout << s << endl;
# define printIf(j,s1,s2) cout << (j ? s1 : s2) << endl;
# define YES(j) cout << (j ? "YES" : "NO") << endl;
# define Yes(j) std::cout << (j ? "Yes" : "No") << endl;
# define yes(j) std::cout << (j ? "yes" : "no") << endl;
# define all(v) v.begin(),v.end()
# define showVector(v) REP(i,v.size()){p(v[i]);p(" ")} pl("")
template<class T> inline bool chmin(T &a, T b){ if(a > b) { a = b; return true;} return false;}
template<class T> inline bool chmax(T &a, T b){ if(a < b) { a = b; return true;} return false;}
typedef long long int ll;
typedef pair<ll,ll> P_ii;
typedef pair<double,double> P_dd;

template<class T>
vector<T> make_vec(size_t a){
    return vector<T>(a);
}

template<class T, class... Ts>
auto make_vec(size_t a, Ts... ts){
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

template<typename T,typename V>
typename enable_if<is_class<T>::value==0>::type
fill_v(T &t,const V &v){t=v;}

template<typename T,typename V>
typename enable_if<is_class<T>::value!=0>::type
fill_v(T &t,const V &v){
  for(auto &e:t) fill_v(e,v);
}


const int MOD = 1000000007;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;

void addM(long long &a, long long b) {
    a += b;
    if (a >= MOD) a -= MOD;
}

void mulM(long long &a, long long b) {
    a = ((a%MOD)*(b%MOD))%MOD ;
}

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

    int N = (1 << n);

    multiset<int> T;
    vector<int> V(1);

    REP(i, N) {
        int s;
        cin >> s;
        T.insert(s);
        chmax(V[0], s);
    }

    REP(i, n){
        int nv = V.size();
        REP(j, nv){
            auto ite = T.lower_bound(V[j]);
            if(ite == T.begin()){
                cout << "No" << endl;
                return 0;
            }
            ite--;
            V.push_back(*ite);
            T.erase(ite);
        }
    }
    cout << "Yes" << endl;

    return 0;
}


Measured memory_bytes: 13692
#include <bits/stdc++.h>
using namespace std;
int n, D1, D2, C1[605][605], C2[605][605];
bool vis[605][605];
vector<pair<int, int> > vec;
inline bool inrange(int x, int y) { return x >= 0 && x < 2 * n && y >= 0 && y < 2 * n; }
void go(int x, int y, int cur, int D, int C[][605]) {
	C[x][y] = cur;
	vis[x][y] = true;
	for (auto &P : vec) {
		int nx = x + P.first, ny = y + P.second;
		if (inrange(nx, ny) && !vis[nx][ny]) go(nx, ny, cur ^ 1, D, C);
		nx = x + P.first, ny = y - P.second;
		if (inrange(nx, ny) && !vis[nx][ny]) go(nx, ny, cur ^ 1, D, C);
		nx = x - P.first, ny = y + P.second;
		if (inrange(nx, ny) && !vis[nx][ny]) go(nx, ny, cur ^ 1, D, C);
		nx = x - P.first, ny = y - P.second;
		if (inrange(nx, ny) && !vis[nx][ny]) go(nx, ny, cur ^ 1, D, C);
	}
}
inline void work(int D, int C[][605]) {
	memset(vis, false, sizeof(vis));
	vec.clear();
	for (int i = 0; i * i <= D; i++) {
		int j = round(sqrt((double)(D - i * i)));
		if (i * i + j * j == D) vec.push_back(make_pair(i, j));
	}
	for (int i = 0; i < 2 * n; i++) {
		for (int j = 0; j < 2 * n; j++) if (!vis[i][j]) go(i, j, 0, D, C);
	}
}
int Cnt[2][2];
int main() {
	scanf("%d%d%d", &n, &D1, &D2);
	work(D1, C1);
	work(D2, C2);
	for (int i = 0; i < 2 * n; i++) for (int j = 0; j < 2 * n; j++) Cnt[C1[i][j]][C2[i][j]]++;
	int mx = max(max(Cnt[0][0], Cnt[0][1]), max(Cnt[1][0], Cnt[1][1]));
	int ac1, ac2;
	if (Cnt[0][0] == mx) ac1 = 0, ac2 = 0;
	else if (Cnt[0][1] == mx) ac1 = 0, ac2 = 1;
	else if (Cnt[1][0] == mx) ac1 = 1, ac2 = 0;
	else ac1 = 1, ac2 = 1;
	int lim = n * n;
	for (int i = 0; i < 2 * n && lim; i++) {
		for (int j = 0; j < 2 * n && lim; j++) {
			if (C1[i][j] == ac1 && C2[i][j] == ac2) {
				lim--;
				printf("%d %d\n", i, j);
			}
		}
	}
	return 0;
}

Measured memory_bytes: 32256
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
using ll = long long;
 
int main()
{
  string s, t;
  cin >> s >> t;
  
  int ls = s.length();
  int lt = t.length();
  int ans = 0;
  
  rep(i,ls-lt+1){
    int cnt = 0;
    rep(j,lt){
      if(s[j+i] == t[j]) ++cnt;
    }
    ans = max(cnt,ans);
  }  
  cout << lt-ans << endl; 
  return 0;
  
}

Measured memory_bytes: 3600
require 'prime'

class Integer
  def divisor_list
    return [] if self <= 0
    return [1] if self == 1

    prime_division.map{|e| [*(0..e.last)].map{|v| e.first ** v }}.inject{|res, e| res.map{|t| e.map{|v| t * v}}.flatten}.sort
  end
end

class Array
  def upper_bound(val)
    a = 0
    b = size

    while a < b
      c = (( a + b ) / 2 ).to_i

      if val < at(c)
        b = c
      else
        a = c + 1
      end
    end

    b
  end

  def lower_bound(val)
    a = 0
    b = size

    while a < b
      c = (( a + b ) / 2 ).to_i

      if val <= at(c)
        b = c
      else
        a = c + 1
      end
    end

    b
  end
end

class Solver
  def initialize
    a, b, c = gets.chomp.split(' ').map(&:to_i)

    divisor_list = c.divisor_list

    n = divisor_list.lower_bound(a)
    m = divisor_list.upper_bound(b)

    puts m - n
  end
end

Solver.new

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

#define rep(i,x,y) for(int i=(x);i<(y);++i)
#define debug(x) #x << "=" << (x)

#ifdef DEBUG
#define _GLIBCXX_DEBUG
#define print(x) std::cerr << debug(x) << " (L:" << __LINE__ << ")" << std::endl
#else
#define print(x)
#endif

const int inf=1e9;
const int64_t inf64=1e18;
const double eps=1e-9;

template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec){
    os << "[";
    for (const auto &v : vec) {
    	os << v << ",";
    }
    os << "]";
    return os;
}

int damerau_levenshtein_distance(const string &a,const string &b,const int alphabet_size){
    map<int,int> da;
    map<int,map<int,int>> d;
    int maxdist=a.size()+b.size();
    d[-1][-1]=maxdist;
    for(int i=0; i<=a.size(); ++i){
        d[i][-1]=maxdist;
        d[i][0]=i;
    }
    for(int i=0; i<=b.size(); ++i){
        d[-1][i]=maxdist;
        d[0][i]=i;
    }
    for(int i=1; i<=a.size(); ++i){
        int db=0;
        for(int j=1; j<=b.size(); ++j){
            int k=da[b[j-1]],l=db,cost;
            if(a[i-1]==b[j-1]){
                cost=0;
                db=j;
            }else cost=1;
            d[i][j]=min({d[i-1][j-1]+cost,d[i][j-1]+1,d[i-1][j]+1,d[k-1][l-1]+(i-k-1)+1+(j-l-1)});
        }
        da[a[i-1]]=i;
    }
    return d[a.size()][b.size()];
}

void solve(int n){
    int d;
    vector<string> name(n);
    cin >> d;
    rep(i,0,n) cin >> name[i];
    sort(name.begin(),name.end());

    int count=0;
    rep(i,0,n){
        rep(j,i+1,n){
            if(damerau_levenshtein_distance(name[i],name[j],26)>d) continue;
            ++count;
            cout << name[i] << "," << name[j] << endl;
        }
    }
    cout << count << endl;
}

int main(){
    std::cin.tie(0);
    std::ios::sync_with_stdio(false);
    cout.setf(ios::fixed);
    cout.precision(10);
    for(;;){
        int n;
        cin >> n;
        if(!n) break;
        solve(n);
    }
    return 0;
}

Measured memory_bytes: 3200