akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;
string board[60];
const int dx[] = {1,0,-1,0};
const int dy[] = {0,1,0,-1};
int main(){
    int h,w; cin >> h >> w;
    for(int i=0; i < h; i++) cin >> board[i];
    for(int i=0; i < h; i++){
        for(int j=0; j < w; j++){
            if(board[i][j] == '.') continue;
            int cnt = 0;
            for(int k=0; k < 4; k++){
                int x = i + dx[k];
                int y = j + dy[k];
                if(x < 0 || x > h) continue;
                if(y < 0 || y > w) continue;
                if(board[x][y] == '#') cnt++;
            }
            if(cnt == 0){cout << "No" << endl; return 0;}
        }
    }
    cout << "Yes" << endl;
    return 0;
}

Measured memory_bytes: 256
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<queue>
#include<deque>
#include<stack>
#include<string>
#include<string.h>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#include<stdlib.h>
#include<cassert>
#include<time.h>
#include<bitset>
using namespace std;
const long long mod=1000000009;
const long long mod2=1000000007;

const long long inf=mod*mod;
const long long d2=(mod+1)/2;
const long double EPS=1e-13;
const long double PI=acos(-1.0);
int ABS(int a){return max(a,-a);}
long long ABS(long long a){return max(a,-a);}
long double ABS(long double a){return max(a,-a);}
char in[40];
vector<pair<long long,long long> >zh[20];
char tmp[40];
const long long key=10007;

int main(){
	int a;scanf("%d",&a);
	scanf("%s",in);
	for(int i=0;i<(1<<a);i++){
		int sz=0;
		int nc=0;
		for(int j=0;j<a;j++){
			if(i&(1<<j)){
				tmp[sz++]=in[j];
				nc++;
			}
		}
		for(int j=a-1;j>=0;j--){
			if(i&(1<<j))continue;
			tmp[sz++]=in[j];
		}
		long long hash=0;
		long long hash2=0;
		
		for(int j=0;j<sz;j++){
			hash=(hash*key)%mod;
			hash+=tmp[j];
			hash%=mod;
			hash2=(hash2*key)%mod2;
			hash2+=tmp[j];
			hash2%=mod2;
		}

	//	printf("%s: %lld\n",tmp,hash);
		zh[nc].push_back(make_pair(hash,hash2));
	}
	for(int i=0;i<=a;i++){
		std::sort(zh[i].begin(),zh[i].end());
	}
	long long ret=0;
	for(int i=0;i<(1<<a);i++){
		int sz=0;
		int nc=0;
		for(int j=a-1;j>=0;j--){
			if(i&(1<<j))continue;
			tmp[sz++]=in[a+j];
			nc++;
		}
		for(int j=0;j<a;j++){
			if(i&(1<<j))tmp[sz++]=in[a+j];
		}
		long long hash=0;
		long long hash2=0;
		
		for(int j=0;j<sz;j++){
			hash=(hash*key)%mod;
			hash+=tmp[j];
			hash%=mod;
			hash2=(hash2*key)%mod2;
			hash2+=tmp[j];
			hash2%=mod2;
		}
		ret+=upper_bound(zh[nc].begin(),zh[nc].end(),make_pair(hash,hash2))-lower_bound(zh[nc].begin(),zh[nc].end(),make_pair(hash,hash2));
	}
	printf("%lld\n",ret);
}

Measured memory_bytes: 5516
#
# def merge_sort(s)
#   tmp = s
#   return tmp if tmp.length <= 1
#   half(s).map { |e| e.merge_sort }
#   merge(a, b)
# end
#
# def half(s)
#   length = s.length
#   mid = (length/2)
#   a = s.slice!(0...mid)
#   b = s.slice!(mid..-1)
#   return [a, b]
# end
#
# def merge(a, b)
#   output = []
#   until a.empty? && b.empty?
#       if a.empty?
#         output.push(b.shift)
#       elsif b.empty?
#         output.push(a.shift)
#       elsif a.first <= b.first
#         output.push(a.shift)
#       else
#         b.shift
#       end
#       return output
#   end
# end
#
# p merge_sort([2, 4, 3, 7, 5, 67, 5,4,4, 8,7,6,5,546,362,245,56266,23,6,234,234,3425,25 ])





# def merge_sort(a, n)
#   return  if n <= 1
#
#   # a ?????????????????????
#   mid = n / 2
#   merge_sort(a, mid)
#
#   # a ???????????? b ???????????????????????????
#   b = a[mid..(n - 1)]
#   merge_sort(b, n - mid)
#
#   # a ???????????? a ?????????????????????
#   a[(n - mid)..(n - 1)] = a[0..(mid - 1)]
#
#   # a ???????????¨ b ?????§?°?????????????????????????
#   ri = 0
#   ai = n - mid
#   bi = 0
#   while bi < n - mid
#     if ai < n && a[ai] <= b[bi]
#       a[ri] = a[ai]
#       ai += 1
#     else
#       a[ri] = b[bi]
#       bi += 1
#     end
#     ri += 1
#   end
# end
@cnt = 0
def msort(a)
  l = a.length
  if l <= 1
    return a
  end
  al = msort(a[0..((l-1)/2)])
  ar = msort(a[((l+1)/2)..(l-1)])
  i = 0
  while i < l do
    if al[0] < ar[0]
      a[i] = al.shift
    else
      a[i] = ar.shift
    end
    i += 1
    if al.length == 0
      while i < l do
        a[i] = ar.shift
        i += 1
        @cnt += 1
      end
    elsif ar.length == 0
      while i < l do
        a[i] = al.shift
        i += 1
        @cnt += 1
      end
    end
     @cnt += 1
  end
  return a
end


n = gets.chomp.to_i
input_array = gets.chomp.split.map(&:to_i)
output = msort(input_array)
puts output.join(' ')
puts @cnt

Measured memory_bytes: 80104
//#pragma GCC optimize(2)
// Happy TLE and WA every day!
// by: zxb the vegetable chicken
#include<bits/stdc++.h>
#define mp              make_pair
#define rep(i,n)        for(int i = 0; i < n; i++)
#define foreach(i,c)    for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define BINF            0x7fffffff
#define INF             0x3f3f3f3f
#define LINF            4557430888798830399
#define END(s)          {cout<<s; return 0;}
#define CON(s)          {cout<<s; continue;}
#define BRE(s)          {cout<<s; break;}
#define pb              push_back
#define All(a)          a.begin(), a.end()  //with A in CAPITAL!!!
#define sz(a)           (int)a.size()
#define F               first
#define S               second
#define Time            clock()/CLOCKS_PER_SEC
//#define usingFiles
using namespace std;

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

inline bool Read(int& x){
	x = 0;
	int c;
	int sign = 1;
	while( (c = getchar()) < '0' || c > '9' ) if(c == '-') sign = -1;
	x = c ^ '0';
	while( (c = getchar()) >= '0' && c <= '9' ) x = (x<<3) + (x<<1) + (c ^ '0');
	x *= sign;
	return 1;
}

inline bool Write(int x){
	if(x >= 10) Write(x / 10);
	putchar(x % 10 + '0');
	return 1;
}

const int rp = 666666;
const bool debug = 1;
const bool I_good_vegetable_a = 1;
const int dx[] = {1, 0, -1, 0};
const int dy[] = {0, 1, 0, -1};

string s;
bool b[440][440];
bool used[440][440];
bool usede[880][880];
int n, m;
ll cnt1, cnt2;
long long res = 0ll;

bool inr(int x, int y){
	return x >= 0 && x < n && y >= 0 && y < m;
}

inline pii Get(int x1, int y1, int x2, int y2){
	if(x1 == x2){
		return mp(x1 * 2, min(y1, y2) * 2 + 1);
	} else {
		return mp(min(x1, x2) * 2 + 1, y1 * 2);
	}
}

void dfs(int x, int y){
	if(b[x][y]) cnt1++;
	else cnt2++;
//	cout << x << " " << y << "   " << cnt1 << " " << cnt2 << endl;
	used[x][y] = 1;
	rep(i, 4){
		int nx = x + dx[i];
		int ny = y + dy[i];
		if(!inr(nx, ny) || used[nx][ny] || b[nx][ny] == b[x][y]) continue;
		dfs(nx, ny);
	}
}

signed main(){
	ios::sync_with_stdio(false);
	#ifdef usingFiles
		freopen("input.txt", "r", stdin);
		freopen("output.txt", "w", stdout);
	#endif
	cin >> n >> m;
	rep(i, n){
		cin >> s;
		rep(j, m){
			if(s[j] == '#') b[i][j] = 1;
			else b[i][j] = 0;
		}
	}
	rep(i, n){
		rep(j, m){
			if(b[i][j] && !used[i][j]){
				cnt1 = cnt2 = 0ll;
				dfs(i, j);
				res += cnt1 * cnt2;
			}
		}
	}
	cout << res << endl;
	return 0;
}
/*
4 4
.#.#
#.#.
.#.#
#.#.
*/

Measured memory_bytes: 8064
#include <bits/stdc++.h>
typedef long long ll;
typedef long double ld;
using namespace std;

ll inf=9223372036854775806;

int main()
{
	//freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
	ios_base::sync_with_stdio(false); cin.tie(0);
	ll i,n,c[500],s[500],f[500],s1=0,j;
	cin>>n;
	for (i=0;i<n-1;i++){
		cin>>c[i]>>s[i]>>f[i];
	}
	for (i=0;i<n-1;i++){
		for (j=i;j<n-1;j++){
			if (i==j){
				s1+=c[i]+s[i];
			}
			else {
				if (s1<=s[j]){
					s1+=s[j]-s1+c[j];
				}
				else {
					if (s1%f[j]==0){
						s1+=c[j];
					}
					else {
						while (s1%f[j]!=0){
							s1++;
						}
						s1+=c[j];
					}
				}
			}
		}
		cout<<s1<<"\n";
		s1=0;
	}
	cout<<"0";
	return 0;
}

Measured memory_bytes: 256
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
#define int long long
const int inf=0x3f3f3f3f3f3f3f3f;
int n,m,pre[200100][2],tree[1001000],ans,a[200100],f[200100],x,y;
vector<int>v[200100];
void modify(int t,int l,int r,int pos,int val){
	if(l==r){
		tree[t]=min(tree[t],val);
		return;
	}
	int mid=(l+r)/2;
	if(pos<=mid)modify(t*2,l,mid,pos,val);
	else modify(t*2+1,mid+1,r,pos,val);
	tree[t]=min(tree[t*2],tree[t*2+1]);
}
int query(int t,int l,int r,int L,int R){
	if(l>R||L>r)return inf;
	if(L<=l&&r<=R)return tree[t];
	int mid=(l+r)/2;
	return min(query(t*2,l,mid,L,R),query(t*2+1,mid+1,r,L,R));
}
signed main(){
	scanf("%lld",&n);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		pre[i][0]=pre[i-1][0]+(a[i]==0);
		pre[i][1]=pre[i-1][1]+(a[i]==1);
	}
	memset(f,0x3f,sizeof(f));
	scanf("%lld",&m);
	for(int i=1;i<=m;i++){
		scanf("%lld%lld",&x,&y);
		v[x].push_back(y);
	}
	f[0]=0;
	memset(tree,0x3f,sizeof(tree));
	for(int i=1;i<=n;i++){
		for(int j=0;j<v[i].size();j++){
			int now=v[i][j];
			int minn=min(f[i-1],query(1,1,n,max(i-1,1ll),now));
			if(minn<f[now]){
				f[now]=minn;
				modify(1,1,n,now,minn);
			}
		}
		f[i]=min(f[i],f[i-1]+((a[i]==1)?1:-1));
	}
	printf("%lld\n",f[n]+pre[n][0]);
}

Measured memory_bytes: 23168
package main

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

var sc *bufio.Scanner

func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc = bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, 0), 1000000001*3)
	sc.Split(bufio.ScanWords)
	s := nextStr()
	n := len(s)
	cnt := make(map[rune]int)
	for _, r := range s {
		_, ok := cnt[r]
		switch {
		case ok:
			cnt[r]++
		default:
			cnt[r] = 1
		}
	}

	ans := 1 + (n * (n - 1) / 2)
	for _, c := range cnt {
		ans -= c * (c - 1) / 2
	}
	fmt.Println(ans)
}


Measured memory_bytes: 1280
#include <bits/stdc++.h>
using namespace std;
 
int main(){
long long N;
  cin >> N;
  long long ans=1e18;
  
  for(long long i=1;i*i <= N;++i){
 if( N % i != 0)    continue;
   long long j = N/i;
 ans = min(ans,i+j-2);
  }
cout << ans << endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using ll = long long ;
#define pb push_back
#define mp make_pair
#define pf push_front
#define FOR(i,a,b)           for(int i = a;   i <  (int)(b); ++i)
#define for_rev(i,a,b)       for(int i = b-1; i >= (int)(a); --i)
#define for_it(it, v) for (auto it = v.begin(); it != v.end(); it++)
#define all(v) v.begin(), v.end()
#define sortv sort(all(v))
#define print(v)     \
    for (auto i : v) \
        cout << i << " ";
#define FAST                     \
    ios::sync_with_stdio(false); \
    cin.tie(NULL);               \
    cout.tie(NULL);
typedef pair<int,int> pi;
typedef vector<int> vi;
typedef unordered_set<int> ust;
typedef set<int> st;
typedef unordered_map<int, int> ump;
typedef map<int, int> mi;
#define F first
#define S second
/*****************************************************************************/

int main()
{
	int n ; cin >> n ;
	if(n>=30) cout << "Yes" << endl;
	else cout << "No" << endl;
return 0 ;
}	

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

using namespace std;
const int maxn = 1e5+10;
typedef long long ll;
int a[maxn], b[maxn], c[maxn];
int n;

int main(){
    scanf("%d", &n);
    for(int i = 0 ; i < n; i++){
        scanf("%d", &a[i]);
    }
    sort(a, a+n);
    for(int i = 0 ; i < n; i++){
        scanf("%d", &b[i]);
    }
    for(int i = 0 ; i < n; i++){
        scanf("%d", &c[i]);
    }
    sort(c, c+n);
    ll ans = 0;
    ll pos1, pos2;
    for(int i = 0; i < n; i++){
        pos1 = lower_bound(a, a + n, b[i]) - a;
        pos2 = upper_bound(c, c + n, b[i]) - c;
        pos2 = n - pos2;
        ans += pos1*pos2;
    }
    printf("%lld\n", ans);
    return 0;
}


Measured memory_bytes: 1408
#include<bits/stdc++.h>
using namespace std;
#define int long long
typedef unsigned long long ull;
typedef long double ld;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define PI 3.14159265
const int MOD=1e9+7;


#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define all(a)  (a).begin(),(a).end()

const int N=1e9+7;

int dp[100005];

int power(int a,int b)
{
    if(b==0)
        return 1;
    if(b==1)
        return a%N;
    if(b%2==0)
    {
        int x=power(a,(b/2));
        x=(x*x)%N;
        return x;
    }
    else
    {
        int x=power(a,(b-1)/2);
        x=(x*x)%N;
        x=(x*a)%N;
        return x;
    }
}

int32_t main()
{
   IOS;
   int n,k;
   cin>>n>>k;

   for(int i=k;i>=1;i--)
   {
       dp[i]=power((k/i),n);
       for(int j=i*2;j<=k;j=j+i)
       {
           dp[i]=dp[i]-dp[j];
       }
   }

   int ans=0;
   for(int i=1;i<=k;i++)
   {
       ans=(ans+(dp[i]*i)%N)%N;
   }

   cout<<ans%N<<endl;



}















Measured memory_bytes: 4332
n=int(input())
c0,c1,c2,c3=0,0,0,0

for i in range (n):
    s=input()
    if(s=='AC'):
        c0=c0+1
    if (s=='WA'):
        c1+=1
    if(s=='TLE'):
        c2+=1
    if(s=='RE'):
        c3+=1
print("AC x ",c0)
print("\nWA x ",c1)
print("\nTLE x ",c2)
print("\nRE x ",c3)

Measured memory_bytes: 9052
#include<bits/stdc++.h>
    using namespace std ;
    #define ll long long int
    int main(){
    #ifndef ONLINE_JUDGE
        freopen("in.txt" ,  "r" ,  stdin) ;
    #endif
    //#define ll long long int
       int n,i;
       cin >> n;
       ll sum=0;
       for (int i = 1; i <= (n); ++i)
       {
       	if(!(i%3==0 || i%5==0))
       		sum = sum + i;
       }
       cout << sum;
     
 }

Measured memory_bytes: 3652
N, D = map(int ,input().split())
li = []
for i in range(N):
    l = list(map(int, input().split()))
    li.append(l)
count = 0

for i in range(N-1):
    for j in range(N-1-i):
        a = 0
        for k in range(D):
            a += (li[i][k]-li[j+i+1][k])**2
        a = a**.5
        if a%1 == 0:
            count += 1

print(count)


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

using namespace std;

// (weighted) UnionFind
class UnionFind {
    public:
        UnionFind(int n) : mPar(n), mRnk(n,0), mWeight(n,0) {
            for(int i = 0; i < n; ++i) mPar[i] = i;
        }

        int find(int x){
            if(mPar[x]==x) return x;
            int r = find(mPar[x]); // 経路圧縮
            mWeight[x] += mWeight[mPar[x]]; // 一つ上の親からの累積和
            return mPar[x] = r;
        }

        bool same(int x,int y){
            return find(x) == find(y);
        }

        int weight(int x){
            find(x); // 経路圧縮
            return mWeight[x];
        }

        int diff(int x, int y){
            return weight(y) - weight(x);
        }

        void unite(int x,int y, int w = 0){
            w += weight(x); w -= weight(y);
            x = find(x);
            y = find(y);
            if(x==y) return;
            if(mRnk[x] < mRnk[y]) swap(x,y), w = -w;
            mPar[y] = x;
            mWeight[y] = w;
            if(mRnk[x] == mRnk[y]) ++mRnk[x];
        }

    private:
        vector<int> mPar, mRnk, mWeight;
};

int main(){
    int n,q,c,x,y,z;
    cin >> n >> q;
    UnionFind uf(n);
    for(int i = 0; i < q; ++i){
        cin >> c;
        if(c==0){
            cin >> x >> y >> z;
            uf.unite(x,y,z);
        } else {
            cin >> x >> y;
            if(uf.same(x,y)) cout << uf.diff(x,y) << '\n';
            else cout << '?' << '\n';
        }
    }
    return 0;
}


Measured memory_bytes: 3840
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> pll;

int main() {
  ll n;
  cin >> n;
  vector<ll> a(5);
  for(ll i=0;i<5;i++) {
    cin >> a[i];
    a[i]=(n+a[i]-1)/a[i];
  }
  ll ans=0;
  sort(a.rbegin(),a.rend());
  cout << a[0]+4 << endl;
}

Measured memory_bytes: 256
def is_ok(mid):
    cnt = 0
    for i in range(n):
        cnt += (a[i] - 1) // mid
    return cnt <= k

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

ok = 10 ** 18
ng = 0
while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if is_ok(mid):
        ok = mid
    else:
        ng = mid
print(ok)


Measured memory_bytes: 30900
L, R = map(int, input().split())

if L == 0:
    print(0)
elif not L // 2019 == R // 2019:
    print(0)
else:
    L %= 2019
    R %= 2019
    ans = 2020
    for i in range(L, R):
        for j in range(i+1, R+1):
            tmp = (i * j) % 2019
            if tmp < ans:
                ans = tmp
    print(ans)


Measured memory_bytes: 3060
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define DEBUG 1
using namespace std;
constexpr int kMod = 1000000007;
typedef long long LL;

template<typename T>
istream& operator >> (istream& is, vector<T>& vs){
  for(T& v: vs) is >> v;
  return is;
}

int main() {
  LL N; cin >> N;
  vector<LL> A(N);
  for (LL i = 1; i <= N; ++i) {
    LL a; cin >> a;
    A[i-1] = a - i;
  }
  sort(A.begin(),A.end());

  LL b2 = N/2;
  LL b1 = b2 - 1;
  LL b3 = b2 + 1;

  b1 = max(0LL, b1);
  b3 = min(N-1LL, b3);

  LL score1 = 0, score2 = 0, score3 = 0;
  for (LL v : A) {
    score1 += abs(v - A[b1]);
    score2 += abs(v - A[b2]);
    score3 += abs(v - A[b3]);
  }
  cout << min({score1, score2, score3}) << endl;
}


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

using namespace std;

char s[105], t[105];
vector<char> v;

int main(){
    scanf("%s", s);
    int l = strlen(s);
    for(int i=0;i<l;i++) v.push_back(s[i]);
    v.erase(unique(v.begin(), v.end()), v.end());

    bool ok = 1;
    for(int i=1;i<l;i++){
        if(s[i] != s[i-1]){
            ok = 0;
        }
    }
    if(ok){
        printf("0\n");
        return 0;
    }

    int ans = 1e9;
    for(int i=0;i<v.size();i++){
        for(int j=0;j<l;j++) t[j] = s[j];
        int ll = l;
        for(int j=0;j<l;j++){
            ll--;
            for(int k=0;k<ll;k++){
                if(t[k] == v[i] || t[k+1] == v[i]) t[k] = v[i];
            }

            bool ok = 1;
            for(int k=0;k<ll;k++){
                if(t[k] != v[i]){
                    ok = 0;
                    break;
                }
            }

            if(ok) ans = min(ans, l-ll);
        }
    }
    printf("%d\n", ans);
}


Measured memory_bytes: 256
from numpy import cumsum
N, K = map(int, input().split())
S = input()
*S, = map(int, list(S))
zeros = [0]
ones = [0]
if S[0] == 0:
    ones.append(0)
cnt = 1
now = S[0]
for i in range(1, N):
    if now == S[i]:
        cnt += 1
    else:
        if now == 0:
            zeros.append(cnt)
        else:
            ones.append(cnt)
        cnt = 1
        now = S[i]
if now == 0:
    zeros.append(cnt)
else:
    ones.append(cnt)
if S[-1] == 0:
    ones.append(0)

c_zero = cumsum(zeros)
c_one = cumsum(ones)
# print(zeros)
# print(c_zero)
# print(c_one)
if len(zeros) <= K:
    print(len(S))
else:
    ans = 0
    for i in range(0, len(zeros) - K):
        #print(i, K)
        #print(c_zero[i+K]-c_zero[i], c_one[i+K+1]-c_one[i])
        aaa = c_zero[i+K]-c_zero[i] + c_one[i+K+1]-c_one[i]
        #aaa = sum(zeros[i:i + K]) + sum(ones[i:i + K])+ones[i+K]
        # if (S[-1] != 0 and i == saigo)or (S[0] != 0 and i == 0):
        #aaa += ones[i+K]
        ans = max(aaa, ans)
    print(ans)


Measured memory_bytes: 15672
#include <algorithm>
#include <climits>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
// const ll MOD = 1000000007;
// const int INF = 2000000000;

string S;

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

  if (S == "zyxwvutsrqponmlkjihgfedcba") {
    cout << -1 << endl;
    return 0;
  }

  string ans = "";
  if (S.size() == 26) {
    char c = 'a' - 1;
    int idx = 26;
    for (int i = 25; i >= 0; i--) {
      if (S[i] > c) {
        c = S[i];
      } else {
        idx = i;
        break;
      }
    }

    char last = 'z' + 1;
    for (int i = idx + 1; i < 26; i++) {
      if (S[i] > S[idx]) {
        last = min(last, S[i]);
      }
    }

    ans = S.substr(0, idx) + last;
  } else {
    vector<bool> b(26, false);
    for (int i = 0; i < S.size(); i++) {
      b[S[i] - 'a'] = true;
    }
    char next_c = '0';
    for (int i = 0; i < 26; i++) {
      if (!b[i]) {
        next_c = i + 'a';
        break;
      }
    }
    ans = S + next_c;
  }

  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<list>
#include<string>
#include<cmath>
#include<algorithm>
#include<bitset>
#include<map>

using namespace std;

#define FOR(i,r,n) for(ll i = (ll)(r); i < (ll)(n); i++)
#define RFOR(i,r,n) for(ll i=(ll)(n-1);i>=r;i--)
#define ALL(x) x.begin(),x.end()
#define RALL(x) x.rbegin(),x.rend()
typedef long long int ll;
typedef long double ld;
typedef vector<ll> vll;
typedef vector<string> vs;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef pair<ll, ll> pll;

ll n = 0, m = 0, k = 0, ans = 0, sum = 0, cnt = 0, temp = 0;
string s;
bool flag;

//----------------------------------------------------------------------

#define MAX 100

int main(void) {
  vll a;
  cin >> s;

  FOR(i, 0, s.length()) {
	temp = s[i] - '0';
	a.push_back(temp);
  }

  if (a.size() == 1) {
	cout << a[0] << endl;
	return 0;
  }

  flag = true;

  FOR(i, 1, a.size()) {
	if (a[i] != 9) flag = false;
  }

  ans = a[0] + (a.size() - 1) * 9;

  if (!flag) --ans;

  cout << ans << endl;

  return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define fore(x,a,b) for(int x=a, qwerty=b; x<qwerty; x++)
#define ALL(a) (a).begin(),(a).end()
#define SZ(a) ((int)(a).size())
#define FIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define pb push_back
#define fst first
#define snd second
using namespace std;
typedef long long ll;

const int N=105;
int n, match[2*N], vis[2*N];
vector<int> g[N];
pair<int,int> A[N], B[N];

int dfs(int u){
    if(vis[u])return 0;
    vis[u]=1;
    for(int v : g[u])if(match[v]==-1 || dfs(match[v])){
        match[v]=u;return 1;
    }
    return 0;
}

int solve(){
    int ans=0;
    memset(match,-1,sizeof(match));
    fore(x,0,n){
        memset(vis,0,sizeof(vis));
        ans += dfs(x);
    }
    return ans;
}

int main(){
	cin >> n;
	fore(x,0,n)cin>>A[x].fst>>A[x].snd;
	fore(x,0,n)cin>>B[x].fst>>B[x].snd;
	fore(x,0,n)fore(y,0,n)if(A[x].fst<B[y].fst && A[x].snd<B[y].snd){
	    g[x].pb(n+y);
	}
	cout << solve() << "\n";
}

Measured memory_bytes: 256
internal fun solve(spa: Int, enemies: List<Long>): Long {
    return if (spa >= enemies.size) {
        0
    } else {
        enemies.sortedDescending().subList(spa, enemies.size).sum()
    }

}

fun main(args: Array<String>) {
    var OUTPUT = ""

    val br = System.`in`.bufferedReader()
    val (n, spa) = br.readLine().split(" ").map { it.toInt() }
    val enemies = br.readLine().split(" ").map { it.toLong() }

    OUTPUT += solve(spa, enemies).toString()
    print(OUTPUT)
}


Measured memory_bytes: 81464
#include <stdio.h>

int main() {
  int N, A, B;
  scanf("%d", &N);
  if (N == 1) {
    printf("Hello World\n");
  } else {
    scanf("%d", &A);
    scanf("%d", &B);
    printf("%d\n", A + B);
  }
  return 0;
}


Measured memory_bytes: 128
#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define REPR(i, n) for(int i = n - 1; i >= 0; i--)
#define FOR(i, m, n) for(int i = m; i <= n; i++)
#define FORR(i, m, n) for(int i = m; i >= n; i--)
#define SORT(v, n) sort(v, v+n);
#define VSORT(v) sort(v.begin(), v.end());
#define VSORTR(v) sort(v.rbegin(), v.rend());
#define ALL(v) (v).begin(),(v).end()
 
using ll = long long;
using vll = vector<ll>;
using vvll = vector<vector<ll>>;
using P = pair<ll, ll>;

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

    ll a, b;
    cin >> a >> b;
    ll c = abs(b - a);
    if(c % 2){
        cout << "IMPOSSIBLE" << endl;
    }
    else{
        ll res = min(a, b) + c / 2;
        cout << res << endl;
    }
    return 0;
}

Measured memory_bytes: 256
#pragma GCC optimize ("O3")
#pragma GCC target ("sse4")

#include <bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<pair<int, int> > vpii;
typedef pair<int, int> pii;
typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<double, double> pdd;
#define INF 1000000000
#define MOD 998244353
#define EPSILON 0.00001
#define f first
#define s second
#define pb push_back
#define mp make_pair

#define FOR(i, a, b) for (int i=(a); i<=(signed)(b); i++)
#define F0R(i, a) for (int i=0; i<(signed)(a); i++)
#define RFOR(i, a, b) for (int i=(a); i >= b; i--)

#define MN 105
string s;
ll k;

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

    cin >> s >> k;
    int n = s.length();
    ll cnt = 0;
    ll cons = 0;
    ll st = 0;
    ll nd = 0;
    F0R(i, s.length()-1){
        if(s[i] == s[i+1]) ++st;
        else break;
    }
    RFOR(i, s.length()-1, 1){
        if(s[i] == s[i-1]) ++nd;
        else break;
    }
    //cout << st << " " << nd << "\n";
    FOR(i, st+1, s.length()-nd-2){ //chk bounds
        if(s[i] == s[i+1]) ++cons;
        else{
            cnt += ((cons+1)/2)*k;
            cons = 0;
        }
    }

    //cout << cnt << "\n";
    
    if(s[0] == s[n-1]){
        if(st == n-1){
            cnt += (k*n)/2;
        } else{
            cnt += (st+1)/2;
            cnt += (nd+1)/2;
            cnt += (st+nd+2)/2*(k-1);
        }
    } else{
        cnt += (st+1)/2*k;
        cnt += (nd+1)/2*k;
    }

    cout << cnt << "\n";
    
    return 0;
}


Measured memory_bytes: 256
from collections import deque

def main():
    R,C= map(int,input().split())

    S = [0,0]

    mv = [[1,0],[-1,0],[0,-1],[0,1]]
    MAP = []
    flg = 0
    block = 0
    for _ in range(R):
        t = list(input())
        block += t.count('#')
        MAP.append(t)
    stack = deque([S])
    MAP_c = [[None]*C for _ in range(R)]
    MAP_c[0][0] = 1
    while stack:
        v = stack.popleft()
        for m in mv:
            u = [v[0]+m[0],v[1]+m[1]]
            if u[0] >=0 and u[0] < R and u[1] >= 0 and u[1] < C and MAP[u[0]][u[1]] == '.':
                MAP[u[0]][u[1]] = '#'
                MAP_c[u[0]][u[1]] = MAP_c[v[0]][v[1]] + 1
                stack.append(u)
                if u == [R-1,C-1]:
                    flg = 1

        if flg == 1:
            break

    if flg == 1:
        a = MAP_c[R-1][C-1]
        print(R*C - a - block)
    else:
        print(-1)


main()

Measured memory_bytes: 9404
parseInt(x) = parse(Int, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
	n,m = readline() |> split |> parseMap
	if n*2>=m
		println(m>>1)
	else
		println(n+div(m-2n,4))
	end
end

main()

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

int main() {
  string s; cin >> s;
  if (s == "SUN") cout << 7;
  if (s == "MON") cout << 6;
  if (s == "TUE") cout << 5;
  if (s == "WED") cout << 4;
  if (s == "THU") cout << 3;
  if (s == "FRI") cout << 2;
  if (s == "SAT") cout << 1;
  return 0;
}

Measured memory_bytes: 256
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <string.h>
#include <vector>
using namespace std;

#define ll long long
#define INF (1 << 30)
#define INFLL (1LL << 60)

#define FOR(i,a,b) for(ll i = (a);i<(b);i++)
#define REP(i,a) FOR(i,0,(a))
#define MP make_pair

int main() {
	int a, b;
	cin >> a >> b;
	a--;b--;
	cout << a*b << endl;
	return 0;
}

Measured memory_bytes: 256
#include <iostream>
using namespace std;
int main(){
    string s;
    cin>>s;
    char x=',';
    for (int i = 0; i <20 ; ++i) {
        if (s[i] == x) {
            s[i] = ' ';
        }
    }
     cout<<s<<endl;
    return 0;
}

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

long long N,M;

long long count(long long num,vector<long long>& A) {
  long long res = 0;
  for(int i = 0;i < N;i++) {
    long long r = num - A.at(i);
    int n = lower_bound(A.begin(),A.end(),r) - A.begin();
    int cnt = N - n;
    res += cnt;
  }
  return res;
}

long long sum(long long num,vector<long long>& A) {
  long long res = 0;
  vector<long long> As(N+10);
  for(int i = 0;i < N;i++) As.at(i) = A.at(i);
  for(int i = N-2;i >= 0;i--) {
    As.at(i) += As.at(i+1);
  }

  for(int i = 0;i < N;i++) {
    long long r = num - A.at(i);
    int n = lower_bound(A.begin(),A.end(),r) - A.begin();
    int cnt = N - n;
    res += 1LL*A.at(i)*cnt;
    res += As.at(n);
  }
  return res;
}

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

  vector<long long> A(N);
  for(int i = 0;i < N;i++) cin >> A.at(i);
  sort(A.begin(),A.end());

  long long ok = 0,ng = 4*100010;
  while(ng-ok > 1) {
    int mid = (ok+ng)/2;
    if(count(mid,A) >= M)  ok = mid;
    else ng = mid;
  }

  long long ans = 0;
  ans += (M - count(ok+1,A))*ok;
  ans += sum(ok+1,A);
  cout << ans << endl;


}


Measured memory_bytes: 1792
#include<bits/stdc++.h>
using namespace         std;
#define                 int long long
#define                 pb push_back
#define                 mp make_pair
#define st(arr,a)       memset(arr,a,sizeof arr)
#define                 nl cout<<endl
#define                 real signed
#define                 endl '\n'              
#define bitcount(x)     __builtin_popcountll(x)
const int MOD = 1000000007ll;
#define forn(i,a,b)     for(int i=a;i<=b;i++)
#define rfor(i,a,b)     for(int i=a;i>=b;i--)
#define all(x)          x.begin() , x.end()
#define pi pair<int,int>
#define X first
#define Y second

//int m,n;
int n;





signed main() 
{
	ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 
    
    cin>>n;
    multiset<pair<int,pi>>dc;

    forn(i,0,n-1)
    {
        int a,b,c;
        cin>>a>>b;
        c=a+b;
        dc.insert({c,{a,b}});
    }

    int arr[2];
    arr[0]=arr[1]=0;
    int i=0;
    
    while(dc.size())
    {
        auto temp=*dc.rbegin();
        dc.erase(dc.find(temp));
        arr[i%2]+=(i%2?temp.Y.Y:temp.Y.X);
        i++;
    }


    cout<<arr[0]-arr[1];

    

    

    
     return 0;

}

//       g++ -g c.cpp ; ./a.exe

Measured memory_bytes: 6528
#include<bits/stdc++.h>
using namespace std;
int n, c, k, a[100005], ans;
vector<int> cur;

int main()
{
	scanf("%d%d%d",&n,&c,&k);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	sort(a+1, a+1+n);
	cur.push_back(a[1]);
	for(int i=2;i<=n;i++) {
		if(cur.front()+k < a[i] || cur.size() == c) {cur.clear(); ans++;}
		cur.push_back(a[i]);
	}
	printf("%d\n",ans+1);
}


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

int hantei(int a, int b){
    if(a==1 && b==1){
        return 0;
    }else if(a==1){
        return 2;
    }else if(b==1){
        return 1;
    }

    if (a > b){
        return 2;
    }else if(b >a){
        return 1;
    }else{
        return 0;
    }
}

int main (){
    int a, b;
    cin >> a >> b;
    if(hantei(a,b)==2){
        cout << "Alice" << endl;
    }else if(hantei(a,b)==1){
        cout << "Bob" << endl;
    }else if(hantei(a,b)==0){
        cout << "Draw" << endl;
    }
}


Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
#include <map>
#include <unordered_map>
#include <set>
#include <functional>
#include <iomanip>
#include <bitset>
#include <cassert>
using namespace std;

typedef long long ll;

int main() {
	int a, b, k; cin >> a >> b >> k;
	int cnt = 0;
	vector<int> c;
	for (int i = 1; i <= min(a, b); i++) {
		if (a%i == 0 && b%i == 0) c.push_back(i);
	}
	reverse(c.begin(), c.end());
	cout << c[k - 1] << endl;
	return 0;
}



Measured memory_bytes: 256
#include <iostream>
#define llint long long

using namespace std;

llint n;
llint a[200005];

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

  cin >> n;
  for(int i = 1; i <= n; i++) cin >> a[i];

  llint ans = 0, r = 0, sum = 0;
  for(int l = 1; l <= n; l++){
    while((sum&a[r+1]) == 0 && r+1 <= n){
      r++;
      sum |= a[r];
    }
    ans += r-l+1;
    sum &= ~a[l];
    //cout << l << " " << r << " " << ans << endl;
  }
  cout << ans << endl;

  return 0;
}


Measured memory_bytes: 1792
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int x = 0;
        for (int i = 0; i < n; i++) {
            int num = scanner.nextInt();
            if (num - 1 != i) x++;
        }

        if (x <= 2) System.out.println("YES");
        else System.out.println("NO");
    }
}


Measured memory_bytes: 23252
package main

import "fmt"

func main() {
    var n int
    fmt.Scan(&n)

    ans := 0.0
    for i := 0; i < n; i++ {
        var (
            x float64
            u string
        )
        fmt.Scan(&x, &u)
        if u == "BTC" {
          ans += x * 380000.0
        } else {
          ans += x
        }
    }
    fmt.Println(ans)
}

Measured memory_bytes: 512
#include<iostream>

using namespace std;

bool is_prime(int x){
  if(x<=1) return false;
  for(int i=2;i*i<=x;i++){
    if(x % i == 0) return false;
  }
  return true;
  
}

signed main(){
  int x;
  cin >> x;
  int p = x;
  while(!is_prime(p)) p++;


  cout << p << endl;

  return 0;
}

Measured memory_bytes: 256
package main

import "fmt"

func main() {
	var n int
	var s string
	fmt.Scan(&n, &s)
	x := 0
	max := 0
	for _, v := range s {
		if v == 'I' {
			x++
		}
		if v == 'D' {
			x--
		}
		if max < x {
			max = x
		}
	}
	fmt.Println(max)
}


Measured memory_bytes: 512
import collections
def slove(n, xs):

    count = collections.Counter()

    for i in xs:
        count[i] += 1

    ans = len([value for value in count.values() if value % 2 == 1])
    return ans

if __name__ == "__main__":
    n = int(input())
    xs = [int(input()) for i in range(n)]
    print(slove(n, xs))


Measured memory_bytes: 16628
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <iomanip>

using namespace std;

int main() {
    int n;
    cin>>n;
    double A[n],tmp=0;

    for(int i=0;i<n;i++){
      cin>>A[i];
      tmp+=1/A[i];
    }


   cout<<setprecision(7)<<1/tmp<<endl;
   return 0;
 }


Measured memory_bytes: 256
var lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});
reader.on('line', (line) => {
  lines.push(line);
});
reader.on('close', () => {
  var line = lines[0].split(" ").map(x => Number(x))
  console.log(Math.ceil(line[0] / line[1]))
});

Measured memory_bytes: 22332
#include <cstdio>
#include <algorithm>
long long s[5002][5002], d[5001], O;
int N, M, a[201][5001];
void insert(int *a)
{
	static int q[5001], D, L[5001], R[5001];
	q[D = 0] = 0;
	for (int i = 1; i <= N; i++)
	{
		while (D && a[q[D]] <= a[i])
			D--;
		L[i] = q[D];
		q[++D] = i;
	}
	q[D = 0] = N + 1;
	for (int i = N; i; i--)
	{
		while (D && a[q[D]] < a[i])
			D--;
		R[i] = q[D];
		q[++D] = i;
	}
	for (int i = 1; i <= N; i++)
	{
		s[i][i] += a[i];
		s[L[i]][i] -= a[i];
		s[i][R[i]] -= a[i];
		s[L[i]][R[i]] += a[i];
	}
}
int main()
{
	scanf("%d%d", &N, &M);
	for (int i = 2; i <= N; i++)
	{
		scanf("%lld", d + i);
		d[i] += d[i - 1];
	}
	for (int i = 1; i <= N; i++)
		for (int j = 1; j <= M; j++)
			scanf("%d", a[j] + i);
	for (int i = 1; i <= M; i++)
		insert(a[i]);
	for (int i = N - 1; i; i--)
		for (int j = i + 1; j <= N; j++)
			s[i][j] += s[i][j - 1] + s[i + 1][j] - s[i + 1][j - 1];
	for (int i = 1; i <= N; i++)
		for (int j = i; j <= N; j++)
			O = std::max(O, s[i][j] - d[j] + d[i]);
	printf("%lld\n", O);
}


Measured memory_bytes: 198912
#include <iostream>

#define ABS(x) (((x) > 0) ? (x) : -(x))

using namespace std;

int main(int argc, char *argv[]) {
	int H, W, D;
	cin >> H >> W >> D;

	int xs[90001];
	int ys[90001];

	for (int y = 0; y < H; y++) {
		for (int x = 0; x < W; x++) {
			int A;
			cin >> A;
			xs[A] = x;
			ys[A] = y;
		}
	}

	int ds[90001] = {};

	for (int a = 1; a <= H * W - D; a++) {
		int dx = xs[a+D] - xs[a];
		int dy = ys[a+D] - ys[a];
		ds[a + D] = ABS(dx) + ABS(dy) + ds[a];
	}

	int Q;
	cin >> Q;
	for (int i = 0; i < Q; i++) {
		int L, R;
		cin >> L >> R;
		cout << (ds[R] - ds[L]) << endl;
	}

	return 0;
}

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

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


Measured memory_bytes: 256
use std::io::*;
use std::str::FromStr;

fn parse_line<T: FromStr>() -> T {
    let mut s = String::new();
    stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn parse_line_vec<T: FromStr>() -> Vec<T> {
    let line = parse_line::<String>();
    line.split_whitespace()
        .map(|s| s.parse().ok().unwrap())
        .collect()
}

fn println<T: std::string::ToString>(s: T) {
    println!("{}", s.to_string());
}

// ------------------------------------------------------------------------

fn main() {
    let input = parse_line_vec::<usize>();
    let n = input[0];
    let a = input[1] - 1; // zero-origin
    let b = input[2] - 1;
    let c = input[3] - 1;
    let d = input[4] - 1;

    let mut s = Vec::with_capacity(n + 1);
    let stdin = stdin();
    stdin.lock().read_until(b'\n', &mut s).unwrap();

    const SPACE: u8 = b'.';
    const ROCK: u8 = b'#';

    let need_overtake = c > d;
    let mut can_overtake = false;

    let mut before_last = s[a];
    let mut before = s[a + 1];

    let last_overtake_index = std::cmp::min(c, d) + 1;

    for index in a + 2..std::cmp::max(c, d) {
        let current = s[index];

        if current == ROCK && before == ROCK {
            println("No");
            return;
        }

        if index > b && index <= last_overtake_index && current == SPACE && before == SPACE && before_last == SPACE {
            can_overtake = true;
        }

        before_last = before;
        before = current;
    }

    let ok = !need_overtake || can_overtake;

    println(if ok { "Yes" } else { "No" });
}


Measured memory_bytes: 4352
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstdlib>
using namespace std;
#define REP(i, j) for(int i = 0; i < j; ++i)
#define FOR(i, j, k) for(int i = j; i < k; ++i)
#define P pair<int, int>
const int N = 1000000;
const int RATE = 9973;

int pr[N];

void prime(){
  REP(i, N) pr[i] = 1;
  pr[0] = 0; pr[1] = 0;
  for(int i = 2; i < N; ++i){
    if(!pr[i]) continue;
    for(int j = i + i; j < N; j += i) pr[j] = 0;
  }
  FOR(i, 1, N) pr[i] += pr[i - 1];
}

int main() {
  prime();
  int n;
  while(cin >>n && n){
    //map<int, int> m;
    int ans = 0;
    REP(i, n){
      int p, m; cin >>p >>m;
      //m[p] += (pr[min(N - 1, p + m)] - pr[max(0, p - m - 1)]);
      int tmp = (pr[min(N - 1, p + m)] - pr[max(0, p - m - 1)]);
      if(tmp == 0) --ans;
      else ans += (tmp - 1);
    }
    cout <<ans <<endl;
    //int ans = 0;
    //for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it){
    //  if((*it).second == 0) --ans;
    //  else ans += ((*it).second - 1);
    //}
    //cout <<max(0, ans) <<endl;
  }
  return 0;
}

Measured memory_bytes: 5064
//include
//------------------------------------------
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <ctime>

using namespace std;

//conversion
//------------------------------------------
inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;}
template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();}

//math
//-------------------------------------------
template<class T> inline T sqr(T x) {return x*x;}

//typedef
//------------------------------------------
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef long long LL;

//container util
//------------------------------------------
#define ALL(a)  (a).begin(),(a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define PB push_back
#define MP make_pair
#define SZ(a) int((a).size())
#define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())

//repetition
//------------------------------------------
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n)  FOR(i,0,n)

//constant
//--------------------------------------------
const double EPS = 1e-10;
const double PI  = acos(-1.0);
const LL MOD = 1000000007;

//clear memory
#define CLR(a) memset((a), 0 ,sizeof(a))

//debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

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

	LL a[n];
	LL ans = 0;

	cin >> a[0];
	if (a[0] != 0) {
		cout << -1;
		return 0;
	}


	bool stair = false;

	for (int i = 1; i < n; i++) {
		cin >> a[i];
		dump(i);
		if (a[i] - a[i-1] > 1) {
			cout << -1;
			return 0;
		}

		if (a[i] - a[i-1] == 1) {
			dump(a[i] - a[i-1] == 1);
			if (!stair) {
				ans -= a[i-1];
			}
			stair = true;
		}
		else if (a[i] == a[i-1]) {
			dump(a[i] == a[i-1]);
			if (stair) {
				ans += a[i-1];
				dump(ans);
				stair = false;
			}
			ans += a[i];
			dump(ans);
		}
		else if (a[i] < a[i-1]) {
			dump(a[i] < a[i-1]);
			if (stair) {
				ans += a[i-1];
				dump(ans);
				stair = false;
			}
			ans += a[i];
			dump(ans);
		}

	}
	for (int i = 0; i < n; i++) {
		dump(a[i]);
	}

	if(stair){
		ans += a[n-1];
	}


	cout << ans;

	return 0;
}


Measured memory_bytes: 1920
#ifdef _MSC_VER
#include "stdc++.h"
#endif
#ifdef __GNUC__
#include<bits/stdc++.h>
#endif
using namespace std;

using ll = long long;

//vector
using vi = vector<int>;
using vii = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;

//constant
const double EPS = 1e-10;

#define REP(i, n) for (ll i = 0; i < n; i++)
#define FOR(i, s, e) for (ll i = s; i < e; i++)
#define ALL(x) (x).begin(),(x).end()
#define RALL(x) (x).rbegin(), (x).rend()

//debug
#define DUMP(x)  cerr << #x << " = " << (x) << endl;
#define DEBUG(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << endl;

// vector
//template<typename T> vector<vector<T>> vv(ll H, ll W, T v) { return vector<vector<T>> vec(H, vector<T>(W, v)); }

// view vector
template<typename T> void view(T e) { cout << e << endl; }
template<typename T> void view(const vector<T>& v) { for (const auto& e : v) { cout << e << " "; } cout << endl; }
template<typename T> void view(const vector<vector<T> >& vv) { for (const auto& v : vv) { view(v); } }

// DP
template<class T>bool chmax(T& a, const T& b) { if (a < b) { a = b; return 1; } return 0; }
template<class T>bool chmin(T& a, const T& b) { if (b < a) { a = b; return 1; } return 0; }





// ***************************************

struct Eratos {
    vector<int> primes;
    vector<bool> isprime;
    vector<int> mebius;
    vector<int> min_factor;
 
    Eratos(int MAX) : primes(),
                      isprime(MAX+1, true),
                      mebius(MAX+1, 1),
                      min_factor(MAX+1, -1) {
        isprime[0] = isprime[1] = false;
        min_factor[0] = 0, min_factor[1] = 1;
        for (int i = 2; i <= MAX; ++i) {
            if (!isprime[i]) continue;
            primes.push_back(i);
            mebius[i] = -1;
            min_factor[i] = i;
            for (int j = i*2; j <= MAX; j += i) {
                isprime[j] = false;
                if ((j / i) % i == 0) mebius[j] = 0;
                else mebius[j] = -mebius[j];
                if (min_factor[j] == -1) min_factor[j] = i;
            }
        }
    }
 
    // prime factorization
    vector<pair<int,int>> prime_factors(int n) {
        vector<pair<int,int> > res;
        while (n != 1) {
            int prime = min_factor[n];
            int exp = 0;
            while (min_factor[n] == prime) {
                ++exp;
                n /= prime;
            }
            res.push_back(make_pair(prime, exp));
        }
        return res;
    }
 
    int func(int n) {
        int res = 1;
        while (n != 1) {
            int prime = min_factor[n];
            int exp = 0;
            while (min_factor[n] == prime) {
                ++exp;
                n /= prime;
            }
            res *= exp + 1;
        }
        return res;
    }
};

int main() {

    ll n;
    cin >> n;

    Eratos er = Eratos(10000001);

    ll ans = 0;
    FOR(k, 1, n + 1) {
        ans += k * er.func(k);
    }

    cout << ans << endl;


    return 0;
}



Measured memory_bytes: 86796
# include <bits/stdc++.h>
typedef long long int ll;
typedef long double ld;
# define pb push_back
# define pii pair < int, int >
# define F first
# define S second
# pragma GCC optimize("unroll-loops")
# pragma GCC optimize("Ofast")
# define int long long int
# define sync ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const int N=2e5+100,inf=1e15,mod=998244353 ;

int32_t main(){
    ll n;
    cin >> n;
    string s;
    cin >> s;
    for (int i=0;i<s.size();i++){
        ll e=s[i]-'A';
        e+=n;
        e%=26;
        s[i]=e+'A';
    }
    cout << s;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
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;}

int main(){
    string s; cin >> s;
    string t; cin >> t;
    int ans=0;
    rep(i, 3) {
        if(s[i] == t[i]) ans++;
    }
    cout << ans << endl;

}

Measured memory_bytes: 256
import std;
enum inf(T)()if(__traits(isArithmetic,T)){return T.max/4;}
T scan(T=long)(){return readln.chomp.to!T;}
void scan(T...)(ref T args){auto input=readln.chomp.split;foreach(i,t;T)args[i]=input[i].to!t;}
T[] scanarr(T=long)(){return readln.chomp.split.to!(T[]);}
alias Queue=DList;auto enq(T)(ref Queue!T q,T e){q.insertBack(e);}T deq(T)(ref Queue!T q){T e=q.front;q.removeFront;return e;} 
alias Stack=SList;auto push(T)(ref Stack!T s,T e){s.insert(e);}T pop(T)(ref Stack!T s){T e=s.front;s.removeFront;return e;} 
struct UnionFind(T){T[T]u;ulong[T] rank;@property{bool inc(T e){return e in u;}auto size(){return u.keys.length;}auto dup(){T[] child=u.keys;T[] parent=u.values;auto res=UnionFind!T(child);child.each!(e=>res.add(e));size.iota.each!(i=>res.unite(child[i],parent[i]));return res;}}this(T e){e.add;}this(T[] es){es.each!(e=>e.add);}auto add(T a,T b=a){assert(b.inc);u[a]=a;rank[a];if(a!=b)unite(a,b);}auto find(T e){if(u[e]==e)return e;return u[e]=find(u[e]);}auto same(T a,T b){return a.find==b.find;}auto unite(T a,T b){a=a.find;b=b.find;if(a==b)return;if(rank[a]<rank[b])u[a]=b;else{u[b]=a;if(rank[a]==rank[b])rank[a]++;}}}
struct PriorityQueue(T,alias less="a<b"){BinaryHeap!(T[],less) heap;@property{bool empty(){return heap.empty;}auto length(){return heap.length;}auto dup(){return PriorityQueue!(T,less)(array);}T[] array(){T[] res;auto tp=heap.dup;foreach(i;0..length){res~=tp.front;tp.removeFront;}return res;}void push(T e){heap.insert(e);}void push(T[] es){es.each!(e=>heap.insert(e));}}T look(){return heap.front;}T pop(){T tp=look;heap.removeFront;return tp;}this(T e){ heap=heapify!(less,T[])([e]);}   this(T[] e){ heap=heapify!(less,T[])(e);}}
//END OF TEMPLATE

void main(){
    long n,m;
    scan(n,m);
    auto a=scanarr!long;
    auto ans=n-a.sum;
    (ans<0?-1:ans).writeln;
}


Measured memory_bytes: 3920