← 返回 anthropic 的题目列表Fix Bootloader Program by Swapping One Instruction to Avoid Loop
类型:online_judge
Problem: Fix a Bootloader Program by Swapping One Instruction
You are given a line-by-line instruction file (program). Each line contains an instruction and an integer value. The program starts at line 0 and maintains a global accumulator acc, initially 0.
Supported instructions:
plus x: set acc += x, then execute the next line (pc += 1).
next x: do not modify acc, execute the next line (pc += 1). The parameter x has no effect.
jump x: do not modify acc, jump to line pc + x (pc += x).
Termination rules:
Normal termination: when the program counter pc becomes len(program) (i.e., just past the last line), terminate and return acc.
Loop detection: if an instruction is about to be executed for the second time (i.e., pc lands on a previously visited line), the program is considered stuck in an infinite loop.
It is known that exactly one line is wrong: on that line, jump and next were swapped (so a line that should be jump is written as next, or vice versa). plus is always correct.
Your task is to swap exactly one jump/next (keeping its integer parameter unchanged) so that the program terminates normally. Output the value of acc after the fixed program terminates.
Input Format
Read from stdin:
Line 1: integer n, number of instructions.
Next n lines: op value, where op is plus / next / jump, and value is a signed integer such as +3, -10, or 0.
Output Format
Print a single integer: acc after the fixed program terminates.
Constraints
1 <= n <= 200000
value fits in 32-bit signed integer
There exists exactly one swap of a single jump/next that makes the program terminate normally
Example
Input:
6
plus +1
next +2
jump +3
plus +3
jump -1
plus +2
Output (for format illustration only):
3
Example
Input
6
plus +1
next +2
jump +3
plus +3
jump -1
plus +2
Output
3