#P9810. Sum of Elements in the Final Sequence

    ID: 22956 Type: Default 1000ms 256MiB

Sum of Elements in the Final Sequence

Sum of Elements in the Final Sequence

You are given a series of k integers \(a_{1 \dots k}\). You need to maintain a sequence by processing these integers one by one in order. The operations are as follows:

  • If \(a_i = 0\), remove (pop) the most recently added element from the sequence.
  • Otherwise, add (push) \(a_i\) to the sequence.

After processing all \(k\) numbers, calculate and output the sum of the numbers remaining in the sequence.

Example:

\(a_i\)Sequence
1\(\{1\}\)
3\(\{1,3\}\)
5\(\{1,3,5\}\)
4\(\{1,3,5,4\}\)
0\(\{1,3,5\}\)
0\(\{1,3\}\)
7\(\{1,3,7\}\)
0\(\{1,3\}\)
0\(\{1\}\)
6\(\{1,6\}\)

The final sum is \(1 + 6 = 7\).

inputFormat

The first line contains a single integer \(k\), the number of operations.

The second line contains \(k\) space-separated integers \(a_1, a_2, \dots, a_k\).

outputFormat

Output a single integer, the sum of the numbers remaining in the sequence after performing all operations.

sample

10
1 3 5 4 0 0 7 0 0 6
7