Canadian Computing Competition: 2015 Stage 1, Senior #1
Your boss has asked you to add up a sequence of positive numbers to determine how much money your company made last year.
Unfortunately, your boss reads out numbers incorrectly from time to time.
Fortunately, your boss realizes when an incorrect number is read and says “zero”, meaning “ignore the current last number.”
Unfortunately, your boss can make repeated mistakes, and says “zero” for each mistake.
For example, your boss can say “One, three, five, four, zero, zero, seven, zero, zero, six”, which means the total is 7 as explained in the following chart.
| Boss statement(s) | Current numbers | Explanation |
|---|---|---|
| “One, three, five, four” | 1, 3, 5, 4 | Record the first four numbers. |
| “zero, zero” | 1, 3 | Ignore the last two numbers. |
| “seven” | 1, 3, 7 | Record the number 7 at the end of our list. |
| “zero, zero” | 1 | Ignore the last two numbers. |
| “six” | 1, 6 | We have read all numbers, and the total is 7. |
At any point, your boss will have said at least as many positive numbers as “zero” statements. If all positive numbers have been ignored, the sum is zero.
Write a program that reads the sequence of boss statements and computes the correct sum.
Input Specification
The first line of input contains the integer which is the number of integers (including “zero”) your boss will say. On each of the lines, there will either be one integer between and (inclusive) or the integer .
Output Specification
The output is one line, containing the integer which is the correct sum of the integers read, taking the “zero” statements into consideration. You can assume that the output will be an integer in the range and (inclusive).
Sample Input 1
Copy
4
3
0
4
0
Sample Output 1
Copy
0
Sample Input 2
Copy
10
1
3
5
4
0
0
7
0
0
6
Sample Output 2
Copy
7
Solution
import java.util.*;
import java.io.*;
public class G {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
public static void main(String[] args) throws IOException {
int num = readInt();
Stack<Integer> sum = new Stack<>();
for(int i=0; i < num; i++) {
int s = readInt();
if(s==0) {
sum.pop();
}else {
sum.add(s);
}
}
long ans = 0;
for(int i=0; i < sum.size(); i++) {
ans += sum.get(i);
}
System.out.println(ans);
}
//8068157774 8073974617
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readCharacter() throws IOException {
return next().charAt(0);
}
static String readLine() throws IOException {
return br.readLine().trim();
}
}