#include <iostream>
#include <stack>
using namespace std;
int main()
{
long long i, a, j, cnt=0;
stack<int> st;
cin>>a;
for(i=1;i<=a;i++)
{
cin>>j;
if(j!=0)
{
st.push(j);
cnt+=j;
}
else
{
cnt-=st.top();
st.pop();
}
}
cout<<cnt;
}