#K47912. Score and Remaining Items
Score and Remaining Items
Score and Remaining Items
You are given a sequence of integers that you must process using a stack-based procedure. For each integer in the sequence, if the stack is not empty and the top element is equal to the current integer, remove the top element from the stack and add the integer's value to your total score. Otherwise, push the current integer onto the stack.
Formally, let \( S \) be the stack and \( total \) be the total score. For each integer \( a_i \) in the sequence, perform the following:
\[ \text{if } S \neq \emptyset \text{ and } S_{top} = a_i: \quad total = total + a_i, \quad pop(S) \quad \text{else:} \quad push(S, a_i) \]At the end, output the total score, followed by the remaining items in the stack in order. If there are no remaining items, output an empty line for the second line.
inputFormat
The input is given via standard input (stdin) and consists of:
- An integer \( n \) indicating the number of elements in the sequence.
- A line with \( n \) space-separated integers.
outputFormat
Output the result to standard output (stdout) in the following format:
- The first line contains the total score.
- The second line contains the remaining items in the stack separated by a single space. If there are no remaining items, output an empty line.
7
1 2 2 3 3 3 4
5
1 3 4
</p>