#include <bits/stdc++.h>

using namespace std;
// Constants and macros
#define INF 		(int)1e9
#define EPS 		1e-9
#define bitcount 	__builtin_popcount
#define gcd 		__gcd
#define forall(i,a,b) 	for(int i=a;i<b;i++)
#define pb 		push_back
#define mp		make_pair
#define MAX(a,b)	( (a)>(b) ? (a):(b))
#define MIN(a,b)	( (a)<(b) ? (a):(b))
#define s(a)		scanf("%d", &a)
#define ss(a,b)		scanf("%d %d", &a,&b)
#define sss(a,b,c)	scanf("%d %d %d", &a,&b,&c)
#define sl(a)		scanf("%I64d", &a)

int K;
int KK[100000];

int main(){
	s(K);
	long long ans = 0;
	int ind = 0;
	int tmp;
	forall(i,0,K){
		s(tmp);
		if (tmp == 0){
			ind--;
			ans-=KK[ind];
		}
		else {
			ans+= tmp;
			KK[ind] = tmp;
			ind ++;
		}
	}
	cout << ans;
}