Variable X with SNAP and ROLLBACK
Python
Hard
3 views
Problem Description
You have one variable x starting at 0. You get q commands: SET v, ADD v, MUL v, SNAP, ROLLBACK. SNAP saves current x. ROLLBACK restores x to the last saved SNAP and removes that SNAP. If there is no SNAP, ROLLBACK does nothing. Output final x.
Input Format
First line q. Next q lines commands.
Output Format
One integer final x.
Sample Test Case
Input:
8
ADD 5
SNAP
MUL 3
ADD 2
ROLLBACK
ADD 1
ROLLBACK
SET 10
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
q=int(lines[0].strip())
x=0
snaps=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if not parts: continue
cmd=parts[0]
if cmd=='SNAP':
snaps.append(x)
elif cmd=='ROLLBACK':
if snaps:
x=snaps.pop()
else:
v=int(parts[1])
if cmd=='SET':
x=v
elif cmd=='ADD':
x+=v
else:
x*=v
sys.stdout.write(str(x))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!